【问题标题】:when i increment the counter it increases by 2 not one. i am using react context for this当我增加计数器时,它增加了 2 而不是 1。我为此使用反应上下文
【发布时间】:2020-10-04 11:56:07
【问题描述】:

这里我调用了一个函数 addItem 来增加购物车的价值

 <CartItem
                key={`cartItem-${item.item_id}`}
                onIncrement={() => addItem(item)}
                onDecrement={() => removeItem(item)}
                onRemove={() => removeItemFromCart(item)}
                data={item}
              />

我的上下文是

const addItemHandler = (item, quantity = 1) => {
    dispatch({ type: 'ADD_ITEM', payload: { ...item, quantity } });
  };

我的 reducer 用于在 reducer.js 中添加项目

export const addItemToCart = (state, action) => {
  const existingCartItemIndex = state.items.findIndex(
    (item) => item.item_id === action.payload.item_id
  );
  if (existingCartItemIndex > -1) {
    const newState = [...state.items];
    newState[existingCartItemIndex].quantity += action.payload.quantity;
    return newState;
  }
  return [...state.items, action.payload];
};
const reducer = (state, action) => {
  switch (action.type) {
    case 'ADD_ITEM':
      return { ...state, items: addItemToCart(state, action) };
    default:
      throw new Error(`Unknown action: ${action.type}`);
  }
};

此代码将计数器增加 2 而不是 1。

【问题讨论】:

  • combineReducer 长什么样子?

标签: reactjs react-context


【解决方案1】:

您的数量被增加两次的原因是因为您将使用React.StrictMode 两次调用您的减速器。

这是故意行为,它有助于检测副作用。一定要注意,如果你的 reducer 是纯函数,就不会出现这样的效果。

在您的情况下,您已经改变了 state 中的数量值,这就是您双倍增量的原因。即使您使用扩展语法来复制数组,它也只执行浅复制,并且其中的内部对象仍然持有相同的引用。

要正确更新它,您必须以不可变的方式更新 reducer。为此,您可以使用Array.prototype.slice

export const addItemToCart = (state, action) => {
  const existingCartItemIndex = state.items.findIndex(
    (item) => item.item_id === action.payload.item_id
  );
  if (existingCartItemIndex > -1) {
        const newState = [
           ...state.items.slice(0, existingCartItemIndex),
           {...state.items[existingCartItemIndex], quantity: state.items[existingCartItemIndex].quantity + 1},
           ...state.items.slice(existingCartItemIndex + 1)
        ];
        return newState;
    }
  return [...state.items, action.payload];
};

【讨论】:

  • 但是当我第一次将商品添加到购物车时,它会给出错误“TypeError: Cannot read property 'quantity' of undefined”
  • 似乎您删除了现有CartItem 为假的其他条件。我用整个函数的样子更新了我的帖子
  • 感谢您的回答。我放错了这段代码。现在一切正常。
  • @ShubhamKhatri 感谢您的回复,您拯救了我的一天!
猜你喜欢
  • 1970-01-01
  • 2019-09-14
  • 2018-09-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多