React Native/Redux加购时同商品数量累加功能失效问题求解
问题原因
你修改后的代码存在两个核心问题:
- 语法错误:更新商品数量时写了非法的对象属性命名
item.qty,JS对象字面量中直接指定属性名qty即可,不需要前缀item. - 逻辑缺失:仅通过
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
相关产品推荐
相关产品推荐

