【发布时间】:2022-01-10 16:42:05
【问题描述】:
我在调度触发 ADD_TO_CART 类型的操作时遇到问题。当用户单击它时,我想增加购物车中添加的特定数字的数量。我得到的数量数字是:1、3、5、7、9 ..但它们应该只增加 1,如 1、2、3、4、5。为什么我的 if 语句会加倍当我想间接更新状态而不改变它时?非常感谢任何形式的帮助。
这是我的代码:
switch(action.type){
case 'ADD_TO_CART':
let tempCart = [...state.cart];
let specificIndex = state.cart.findIndex((obj) => obj.id === action.item.id);
if(specificIndex >= 0){
tempCart[specificIndex].quantity +=1; // it should increment only by 1 and not by 2
tempCart[specificIndex].price += action.item.price;
return{
...state,
cart : tempCart,
}
}
这是我上面例子的状态:
export const initialState = {
cart: [],
};
【问题讨论】:
-
你确定这个reducer只被调用一次吗?我建议添加一个 console.log("test");到你的reducer代码的第一行,以确保这个reducer只被调用一次。
标签: javascript reactjs state reducers