如何避免商品数量为1时,购物车总金额被扣除商品单价?
购物车商品数量调整的Reducer修复方案
原代码的问题在于执行减少商品数量操作时,无论当前商品数量是否为1,都会扣除该商品单价,不符合需求。以下是修复后的代码:
if (action.type === "UPDATE_ITEM_QUANTITY") { let totalAmount = state.totalAmount; const tempCart = state.items.map(item => { if (item.id === action.payload.id) { if (action.payload.type === "increment") { const newQuantity = item.quantity + 1; totalAmount += item.price; return { ...item, quantity: newQuantity }; } if (action.payload.type === "decrement") { // 仅当商品当前数量大于1时,才执行减数量和扣金额操作 if (item.quantity > 1) { const newQuantity = item.quantity - 1; totalAmount -= item.price; return { ...item, quantity: newQuantity }; } // 数量为1时,直接返回原商品,不修改金额 return item; } } return item; }); return { ...state, items: tempCart, totalAmount: totalAmount }; }
关键改动说明
- 初始化
totalAmount为当前状态的总金额,避免未匹配商品时出现undefined - 在decrement分支增加判断:仅当商品当前数量大于1时,才执行数量递减和总金额扣除
- 若商品数量已经是1,直接返回原商品对象,不做任何金额修改
内容的提问来源于stack exchange,提问作者user19991216
相关产品推荐
相关产品推荐

