reactjs - 当我单击以增加购物车中商品的数量时,它增加了两个而不是一个
问题描述
我遇到了购物车的问题。单击 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 个数量。我该如何解决这个问题
解决方案
看看这里的 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
推荐阅读
- sequelize.js - sequelize-cli:运行单个种子文件很慢
- bash - 在没有root权限的Rhel6.5上安装meld
- python-3.x - 使用'for'循环迭代给定函数的列表
- python - 如何在 DataFrame 中正确设置列
- pine-script - 我怎样才能让每个入口点只有一个出口?
- flutter - Flutter:如何设置父小部件的状态
- c++ - C1189 #错误:
使用 /clr 或 /clr:pure 编译时不支持 - typescript - typescript:如何将类型的属性简化为特定类型的属性?
- c++ - 如何让 GetLocaleInfoEx 以特定语言返回其数据?
- java - 验证多个 URL 并获取哪些有效