React-Native无法添加商品至收藏页,出现TypeError: undefined is not a function
React-Native Context Hook收藏功能修复方案
问题根源分析
你的代码存在4个核心错误,直接导致收藏功能失效并抛出TypeError: undefined is not a function:
- 直接修改state且操作对象而非数组:state是包含
products/cart/FavoritesList的对象,你调用的splice/push是数组方法,对象没有这些方法,这是报错的直接原因;同时React要求state必须保持不可变,不能直接修改原state。 - 操作错误的数组:需求是将商品添加到收藏列表
FavoritesList,但你当前代码操作的是state.products数组,逻辑完全偏离需求。 - 返回错误的状态结构:返回
[...state]会把对象展开成数组,彻底破坏原有state结构,导致组件无法读取FavoritesList。 - CLEAR操作丢失状态:仅返回
{cart:[]}会丢失products和FavoritesList的状态,引发其他功能异常。
修复后的Reducer代码
const initialState = { products: ProductData, // 保留原商品数据 cart: [], FavoritesList: [], }; const reducer = (state = initialState, action) => { switch(action.type) { case 'ADD_PRODUCT_TO_FAVORITE': const product = action.payload; // 检查商品是否已在收藏列表中 const isInFavorites = state.FavoritesList.some(item => item.id === product.id); if (isInFavorites) { // 已收藏则移除,返回新的收藏列表 return { ...state, FavoritesList: state.FavoritesList.filter(item => item.id !== product.id) }; } else { // 未收藏则添加,返回新的收藏列表 return { ...state, FavoritesList: [...state.FavoritesList, product] }; } case 'CLEAR': // 仅清空购物车,保留其他状态 return { ...state, cart: [] }; default: throw new Error(`Unknown action: ${action.type}`); } }
关键修复说明
- 保持状态不可变:每次更新都返回全新的state对象,用
...state保留未修改的状态,仅更新FavoritesList。 - 修正操作目标:改为操作
FavoritesList数组,用some判断收藏状态,filter移除已收藏项,[...arr, item]添加新项。 - 修复状态结构:始终返回与初始state一致的对象结构,避免破坏状态完整性。
- 完善CLEAR逻辑:保留商品数据和收藏列表,仅清空购物车。
额外验证点
确保你的Context Provider正确暴露状态:
const CartContext = createContext(); export const CartProvider = ({ children }) => { const [state, dispatch] = useReducer(reducer, initialState); return ( <CartContext.Provider value={{ ...state, dispatch }}> {children} </CartContext.Provider> ); }; export const useCart = () => useContext(CartContext);
这样收藏页组件中const { FavoritesList } = useCart();才能正确获取到收藏列表数据。
内容的提问来源于stack exchange,提问作者Omar Bakoban
相关产品推荐
相关产品推荐

