You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 17:52:42