首页 > 解决方案 > 当我单击以增加购物车中商品的数量时,它增加了两个而不是一个

问题描述

我遇到了购物车的问题。单击 INCREASE_QTY 增加购物车中现有商品的数量后,它会增加 2 而不是 1。总项目数量正确增加,但单个项目数量现在正确增加。我正在使用带有上下文 API 的 React useReducer 钩子。

 case "ADD_TO_CART":
      if (state.cart.length === 5) {
        return state;
      } else {
        items = action.item;
        items["itemQty"] = 1;   // add single item qty in array 
        updateQty = state.qty + 1; // total items qty
        items["day"] = action.dayItem;
        return {
          cart: [items, ...state.cart],
          qty: updateQty,
        };
      }
    case "INCREMENT_QTY":
      items = action.item;
      items.itemQty = items.itemQty + 1
      updateQty = state.qty + 1
      index = state.cart.findIndex((cart) => cart.id === action.id);
      state.cart[index] = items;
      return {
        cart: [...state.cart],
        qty: updateQty,
      }

单击一次后,我得到了 2 个数量。我该如何解决这个问题

标签: reactjsreact-hooksreact-contextuse-reducer

解决方案


看看这里的 React 文档,了解如何使用上下文实现 Reducer Hook。
https://reactjs.org/docs/hooks-reference.html#usereducer(文档中的 React 示例概述了如何实现上述特定目标。

这是另一个很好的资源,用于将上下文与 Auth 的自定义钩子一起使用,这可能会使 React 模式在更高层次上更容易理解,这对我有所帮助。 https://fatmali.medium.com/use-context-and-custom-hooks-to-share-user-state-across-your-react-app-ad7476baaf32


推荐阅读