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

React使用useReducer调整购物车商品数量时报错页面消失

useReducer购物车增减功能报错排查

你的代码存在3处问题,直接导致运行报错、页面白屏:

  • 核心错误:reducer破坏了cart数组的原有结构
    你写的map遍历逻辑无论商品id是否匹配,返回值都是quantity的数字值,而不是完整的商品对象。原本cart是存储商品对象的数组,执行完逻辑后会变成纯数字数组,后续渲染时读取item.id、item.quantity等属性会直接抛出类型错误,导致整个页面崩溃消失。
  • 传参不匹配:点击事件传错了dispatch的payload值
    你定义的增减函数接收的参数是商品id,但按钮点击事件里传入的是整个item商品对象,导致reducer里x.id === action.payload的判断永远无法成立,就算数组结构没写错也无法正确修改目标商品的数量。
  • 冗余代码:减少数量的逻辑里多套了一层无用的大括号
    虽然这个问题不会直接触发报错,但属于不规范写法,容易引发作用域相关的隐性bug。

修复方案

1. 修正reducer的更新逻辑

map遍历匹配到目标商品时,要返回完整的商品对象,仅更新quantity字段,不要直接返回数字:

if (action.type === "INCREASE_QUANTITY") {
  return {
    ...state,
    cart: state.cart.map((item) =>
      item.id === action.payload 
        ? {...item, quantity: item.quantity + 1} 
        : item
    ),
  };
}

if (action.type === "DECREASE_QUANTITY") {
  return {
    ...state,
    cart: state.cart.map((item) =>
      item.id === action.payload 
        ? {...item, quantity: Math.max(1, item.quantity - 1)} // 限制数量最小为1,避免出现负数
        : item
    ),
  };
}

2. 修正点击事件的传参

给增减函数传参时传入商品id,不要传整个商品对象:

<div className="flex space-x-2 md:space-x-3 items-end mt-4 md:mt-9 md:text-xl">
  <button
    onClick={() => decreaseQuanity(item.id)}
    className="font-bold text-yellow-700 shadow p-2 border-1 rounded-md">
    <FaMinus />
  </button>
  <h3 className="text-2xl">{item.quantity}</h3>

  <button
    onClick={() => increaseQuanity(item.id)}
    className="font-bold text-yellow-700 shadow p-2 border-1 rounded-md">
    <FaPlus />
  </button>
</div>

扩展提示:如果需要实现“数量减到0就自动从购物车移除商品”的效果,可以把减数量的逻辑替换为过滤逻辑:当商品数量已经是1时,直接filter掉当前id的商品即可,不需要保留数量为0的商品项。

内容的提问来源于stack exchange,提问作者Rengkat

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 02:33:42