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

React Native/Redux加购时同商品数量累加功能失效问题求解

问题原因

你修改后的代码存在两个核心问题:

  1. 语法错误:更新商品数量时写了非法的对象属性命名item.qty,JS对象字面量中直接指定属性名qty即可,不需要前缀item.
  2. 逻辑缺失:仅通过map遍历现有购物车更新已存在的商品,没有处理「商品首次加入购物车、原本不在数组中」的场景,所以第一次加购时遍历空数组返回空,购物车自然一直没有数据

正确实现代码

const cart = (state = initialState , action) =>{
  switch (action.type) {
    case 'ADD_TO_CART_PROD':
      // 查找当前要添加的商品是否已在购物车中
      const existIndex = state.cart.findIndex(item => item.id === action.payload.id)
      let newCart
      if (existIndex >= 0) {
        // 商品已存在,仅更新对应商品的数量
        newCart = state.cart.map((item, index) => 
          index === existIndex 
            ? {...item, qty: item.qty + action.payload.qty} 
            : item
        )
      } else {
        // 商品不存在,新增条目到购物车数组
        newCart = [...state.cart, action.payload]
      }
      return {
        ...state,
        cart: newCart,
        qtytotal: state.qtytotal + action.payload.qty
      }     
    default:
      return state
  }
}

以上逻辑可以完美实现需求:同ID商品多次点击加购仅累加数量,不会新增重复对象。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 09:39:02