如何使用useReducer移除作为state的购物车数组中的商品?
如何在useReducer中实现购物车商品移除功能?
我使用useReducer管理应用状态,其中cart数组用来存储已加入购物车的商品(每个商品是包含name、price、id等属性的对象)。目前已经实现了商品添加至购物车的功能,但不清楚如何编写REMOVE_FROM_CART的action逻辑来移除购物车中的商品。
当前的reducer代码示例如下:
export const initialState = { loading: false, products: [], error: false, cart: [], wishlist: [], }; export const productReducer = (state, action) => { switch (action.type) { case actionTypes.FETCHING_START: return { ...state, loading: true, error: false, }; case actionTypes.FETCHING_SUCCESS: return { ...state, loading: false, products: action.payload, error: false, }; case actionTypes.FETCHING_ERROR: return { ...state, loading: false, error: true, }; case actionTypes.ADD_TO_CART: return { ...state, cart: [...state.cart, action.payload], }; case actionTypes.ADD_TO_WISHLIST: return { ...state, wishlist: [...state.wishlist, action.payload], }; case actionTypes.REMOVE_FROM_CART: return { ...state, cart: [...state.cart, action.payload], }; default: return state; } };
可以看到,当前REMOVE_FROM_CART的逻辑是错误的(它把action.payload又添加到了cart数组中)。正确的逻辑应该是通过filter方法过滤掉cart数组中id与action.payload匹配的商品,同时保持state的不可变性:
case actionTypes.REMOVE_FROM_CART: return { ...state, cart: state.cart.filter(item => item.id !== action.payload) };
核心思路说明:
- 利用
Array.filter()返回新数组,自动排除掉需要移除的目标商品 - 遵循reducer纯函数特性,不直接修改原state对象,而是返回包含新cart数组的state副本
内容的提问来源于stack exchange,提问作者Dipto Roy
相关产品推荐
相关产品推荐

