【发布时间】:2021-04-04 06:11:40
【问题描述】:
我正在尝试将 AJAX 调用返回的数据对象存储到 Redux 的减速器状态数组中。 我有一些条件来检查提取的数据是否已经存在于reducer中。
这是我的问题:
- 调用AJAX调用动作的组件,来自
mapDispatchToProps的函数,导致无限循环。 -
减速器中的
isProductLikedData状态未正确更新。
你能说出我错过了什么吗?
这是我的代码:
isProductLikedActions.js - 获取 isProductLiked 数据的操作。 response.data 看起来像 {status: 200, isProductLiked: boolean}
export function fetchIsProductLiked(productId) {
return function (dispatch) {
axios
.get(`/ajax/app/is_product_liked/${productId}`)
.then((response) => {
dispatch({
type: 'FETCH_IS_PRODUCT_LIKED_SUCCESS',
payload: { ...response.data, productId },
});
})
.catch((err) => {
dispatch({
type: 'FETCH_IS_PRODUCT_LIKED_REJECTED',
payload: err,
});
});
};
}
isProductLikedReducer.js - 当array.length === 0 时,我将action.payload 对象添加到isProductLikedData 数组。之后,我想检查action.payload 对象是否存在于isProductLikedData 中以防止重复。如果没有重复,我想做[...state.isProductLikedData, action.payload]。
const initialState = {
isProductLikedData: [],
fetching: false,
fetched: false,
error: null,
};
export default function reducer(state = initialState, action) {
switch (action.type) {
case 'FETCH_IS_PRODUCT_LIKED': {
return { ...state, fetching: true };
}
case 'FETCH_IS_PRODUCT_LIKED_SUCCESS': {
return {
...state,
fetching: false,
fetched: true,
isProductLikedData:
state.isProductLikedData.length === 0
? [action.payload]
: state.isProductLikedData.map((data) => {
if (data.productId === action.payload.productId) return;
if (data.productId !== action.payload.productId)
return action.payload ;
}),
};
}
case 'FETCH_IS_PRODUCT_LIKED_REJECTED': {
return {
...state,
fetching: false,
error: action.payload,
};
}
}
return state;
}
Products.js - products 是在 componentWillMount 中获取的数组。一旦nextProps.products.fetched 变为真,我想调用fetchIsProductLiked 来获取isProductLiked` 数据。但这会导致无限循环。
class Products extends React.Component {
...
componentWillMount() {
this.props.fetchProducts();
}
...
componentWillReceiveProps(nextProps) {
if (nextProps.products.fetched) {
nextProps.products.map((product) => {
this.props.fetchIsProductLiked(product.id);
}
}
render() {
...
}
}
export default Products;
【问题讨论】:
-
你能显示你使用connect for Products组件连接到redux store的代码吗
标签: reactjs redux react-redux