You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何避免商品数量为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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 05:40:22