Redux购物车商品数量减少功能实现咨询及cart.js代码解析
实现带商品数量减少功能的Redux购物车代码片段
我来帮你把这段cart.js里的Redux reducer代码规整好,还补充了没写完的quantityById部分逻辑,让数量减少的功能完整起来:
已添加商品ID数组的Reducer (addedIds)
这个reducer负责维护购物车中所有已添加商品的ID列表,确保不会重复添加同一商品:
const addedIds = (state = initialState.addedIds, action) => { switch (action.type) { case ADD_TO_CART: // 如果商品已在购物车中,直接返回原状态 if (state.indexOf(action.productId) !== -1) { return state } // 否则将新商品ID追加到数组末尾 return [ ...state, action.productId ] case REDUCT_FROM_CART: // 移除指定ID的商品(注意:这里的action类型名可能是笔误,建议改成REDUCE_FROM_CART) return state.filter(productId => action.productId !== productId) default: return state } }
商品数量管理的Reducer (quantityById)
这个reducer负责记录每个商品在购物车中的数量,补充了减少数量的逻辑(当数量减到0时自动移除商品的数量记录):
const quantityById = (state = initialState.quantityById, action) => { switch (action.type) { case ADD_TO_CART: // 如果商品已存在,数量+1;否则初始化为1 return { ...state, [action.productId]: (state[action.productId] || 0) + 1 } case REDUCT_FROM_CART: const currentQuantity = state[action.productId] || 0; if (currentQuantity <= 1) { // 数量小于等于1时,移除该商品的数量记录 const newState = { ...state }; delete newState[action.productId]; return newState; } // 数量大于1时,数量-1 return { ...state, [action.productId]: currentQuantity - 1 } default: return state } }
小提示
- 注意
REDUCT_FROM_CART这个action类型名可能是拼写错误,建议统一改成REDUCE_FROM_CART,避免后续维护时混淆 - 如果你希望商品数量可以减到0但不从购物车中移除,只需要修改
REDUCT_FROM_CART分支的逻辑,直接返回currentQuantity - 1即可,不用删除对应的属性
内容的提问来源于stack exchange,提问作者Lex V
相关产品推荐
相关产品推荐

