【发布时间】:2017-12-13 01:05:22
【问题描述】:
在我的状态下,我有一个对象数组,这些对象具有一些描述性属性、数量和唯一 ID。此对象中的数据来自 API 响应,在我的动作创建器中,我检查状态以查看它是否已经存在,如果存在,则为我的减速器调度增量动作。这是我的动作创建者的样子:
export const getProductDetails = upc => (dispatch, getState) => {
const state = getState();
const products = state.table.products;
if (_find(products, upc) !== undefined) {
dispatch({ type: INCREMENT_QUANTITY, payload: upc });
} else {
axios
.post(<--POST TO ENDPOINT-->) }
})
.then(res => {
dispatch({ type: POST_UPC, payload: res.data });
})
.catch(err => {
errorHandler(dispatch, err.response, AUTH_ERROR);
});
}
};
我在这个案例中的 reducer 的结构如下:
case INCREMENT_QUANTITY:
return {
...state,
products: state.products.map(product => {
action.payload === product.upc
? { ...product, quantity: product.quantity + 1 }
: product;
})
};
我基于这个 reducer 逻辑
this excellent response,但由于某种原因,在调度操作时,重复的产品被覆盖为 null,而不是按预期增加数量。我现在还在努力学习redux,所以请原谅我的无知。理想情况下,我想避免仅仅为了增加值而引入库或包。我的减速器中到底缺少什么?
【问题讨论】:
标签: javascript redux immutability