React Redux中如何更新指定项?我的quantity字段未更新
问题分析与修复
原始代码情况
初始状态(reducer.js)
cart: { id: 100, name: "Pizza", price: 550, category: "Fasting", time: "20-50 min", restaurantId: "BH001", quantity: 1, photo: { fileName: "", fileType: "", filePath: "", }, description:"The food is ...", },
待修复的reducer代码
case "INCREASE_DECREASE_ORDER_AMOUNT": return { ...state, carts: [ ...state.cart.map((val) => { if (val.id === action.payload) { if (action.typo == "+") { return { ...val, quantity: val.quantity + 1, }; } } }), ], };
action代码(action.js)
const increaseDeacreaseOrderAmount = (id, typo) => { return { type: "INCREASE_DECREASE_ORDER_AMOUNT", payload: id, typo: typo, }; }; export { increaseDeacreaseOrderAmount }
调用代码(index.js)
onPress={() => { dispatch(increaseDeacreaseOrderAmount(value.id, "+")); }}
问题根源
- 状态结构不匹配:初始状态是单个
cart对象,但reducer里错误调用了数组的map方法(单个对象无法使用map),还把结果赋值给了不存在的carts字段。 - map函数返回值缺失:没匹配到目标id的元素没有返回值,会导致生成的数组包含
undefined,破坏状态结构。 - 逻辑不完整:只处理了数量增加的情况,没处理减少逻辑,也没有默认返回原状态的分支。
修复方案
情况1:初始状态是单个购物车项(cart对象)
case "INCREASE_DECREASE_ORDER_AMOUNT": // 匹配目标购物车项id if (state.cart.id === action.payload) { let newQuantity = state.cart.quantity; if (action.typo === "+") { newQuantity += 1; } else if (action.typo === "-") { // 限制数量不小于1,避免出现负数 newQuantity = Math.max(1, newQuantity - 1); } // 返回新状态,仅更新quantity字段 return { ...state, cart: { ...state.cart, quantity: newQuantity } }; } // 不匹配则直接返回原状态 return state;
情况2:初始状态是购物车数组(carts数组,可能你之前写错了字段名)
case "INCREASE_DECREASE_ORDER_AMOUNT": return { ...state, carts: state.carts.map((val) => { if (val.id === action.payload) { let newQuantity = val.quantity; if (action.typo === "+") { newQuantity += 1; } else if (action.typo === "-") { newQuantity = Math.max(1, newQuantity - 1); } return { ...val, quantity: newQuantity }; } // 不匹配的项直接返回原对象 return val; }) };
额外优化建议
- 修正action函数名拼写:
increaseDeacreaseOrderAmount改为increaseDecreaseOrderAmount(Deacrease→Decrease),避免命名混淆。 - 把
typo参数改名为operation,语义更清晰。
内容的提问来源于stack exchange,提问作者Hailemelekot
相关产品推荐
相关产品推荐

