我正在编写此应用程序,该应用程序根据登录的用户检查当前产品。我编写了一个redux操作,用于检查该用户的当前产品,但是我不知道如何实现它。有人可以帮我吗?
PS如果我分派操作以检查组件内的当前产品是否安装了生命周期方法,那么react将创建一个无限循环,并且我只想在用户登录后检查产品,因为否则我可以不会检索任何产品。
import { CHECK_PRODUCTS_STARTED, CHECK_PRODUCTS_SUCCESS, CHECK_PRODUCTS_FAILURE } from './types'
const getProducts = () => {
return async (dispatch, getState) => {
dispatch(checkProductsStarted())
let config = {
method: 'POST',
headers: { 'Content-Type':'application/x-www-form-urlencoded' },
body: `token=${getState().auth.token}`
}
// Get database products
const { products: dbProducts } = await fetch('http://localhost:9000/api/getProducts', config)
.then(async res => await res.json())
.catch(err => {
dispatch(checkProductsFailure({error: typeof(err) === "string" || err ? err.toString() : "Error"}))
})
// Get current products in state
const { products: stateProducts } = getState().products
// Only add products that arent already in the state:
const unqiueProducts = dbProducts.filter(product => stateProducts.includes(product))
// Add them to payload
dispatch(checkProductsSuccess(unqiueProducts))
}
}
const checkProductsStarted = () => {
return {
type: CHECK_PRODUCTS_STARTED
}
}
const checkProductsSuccess = (products) => {
return {
type: CHECK_PRODUCTS_SUCCESS,
payload: {
products
}
}
}
const checkProductsFailure = (err) => {
return {
type: CHECK_PRODUCTS_FAILURE,
payload: {
...err
}
}
}
export default getProducts