Redux Reducer设置收藏时出现Cannot read 'find'未定义类型错误
Redux收藏功能报错:Uncaught TypeError: Cannot read properties of undefined (reading 'find')
问题分析
报错的核心原因是**state.favorites在执行find方法时处于undefined状态**,尽管你在initialState中把它初始化为空数组,但可能存在以下情况:
- reducer初始化过程中未正确传入
initialState - 其他action的reducer逻辑意外将
favorites字段覆盖为undefined或null - 你之前尝试的判断写错了变量名(
state.favorite少了末尾的s,导致读取的是不存在的字段)
修复方案
1. 增加防御性检查,确保操作的是数组
修改setFavourite的reducer逻辑,先确认favorites是数组再执行后续操作:
setFavourite: (state, action) => { // 确保favorites始终是数组,避免undefined报错 const currentFavorites = Array.isArray(state.favorites) ? state.favorites : []; const isAlreadyFavorited = currentFavorites.find( (favorite) => favorite.product_id === action.payload.product_id ); if (!isAlreadyFavorited) { const newFavorite = { product_id: action.payload.product_id, favorite: true, }; state.favorites = [...currentFavorites, newFavorite]; } },
2. 排查其他reducer分支
检查所有修改state的reducer case,确认没有其他逻辑错误地将state.favorites设置为undefined或null,比如误写state.favorites = null这类代码。
3. 确认reducer初始化正确
确保在创建store时,正确将包含favorites: []的initialState传入reducer,比如:
const store = createStore(rootReducer, initialState);
补充说明
你之前尝试的state.favorite.length === 0判断报错,是因为变量名拼写错误——应该是state.favorites(复数形式),少了s导致读取的是不存在的字段,自然会触发undefined相关错误。
内容的提问来源于stack exchange,提问作者usmannoor90
相关产品推荐
相关产品推荐

