【问题标题】:React reducer wrong increment number反应减速器错误的增量数
【发布时间】: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


【解决方案1】:

我怀疑这是因为您将tempCart 视为可变(直接添加到其成员),而实际上它只是对(不是副本的引用of) state 的一部分,应始终被视为不可变。相反,请尝试以下操作:

switch (action.type) {
  case "ADD_TO_CART":
    let specificIndex = state.cart.findIndex(
      (obj) => obj.id === action.item.id
    );
    if (specificIndex >= 0) {
      return {
        ...state,
        cart: state.cart.map((item, idx) =>
          idx == specificIndex
            ? {
                ...item,
                quantity: item.quantity + 1,
                price: item.price + action.item.price,
              }
            : item
        ),
      };
    }
}

请参阅Immutable Update Patterns 了解更多信息。请注意,即使在这个小例子中,这些类型的更新也会很快变得笨拙。如果您愿意,可以使用helper libraries 来简化流程。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-06
    • 1970-01-01
    • 2017-09-07
    • 1970-01-01
    • 2017-05-09
    • 1970-01-01
    相关资源
    最近更新 更多