You need to enable JavaScript to run this app. React-Redux用useSelector报Cannot read property 'name'错误
优惠活动
大模型
产品
解决方案
定价
更多

React-Redux用useSelector报Cannot read property 'name'错误

核心错误原因
  • 状态结构与读写逻辑不匹配
    todoSlice中定义的初始状态为纯数组结构,数组元素直接是包含id、name、description字段的Todo条目。但在todoUpdated reducer的查找逻辑中,错误使用了state.entities[id]的对象取值方式——当前状态树中根本不存在entities嵌套对象,因此existingTodo永远为undefined,更新逻辑完全无法生效。
  • 组件取值缺少兜底判断
    通过useSelector从store提取对应Todo条目时,若未匹配到对应id的条目,返回值为undefined,此时直接链式读取name属性,就会抛出Cannot read property 'name' of undefined的控制台错误。
可直接落地的修复步骤
  • 修正todoSlice的条目查找逻辑
    将todoUpdated reducer中错误的对象取值方式,替换为数组匹配逻辑:
    todoUpdated(state, action) {
      const { id, name, description } = action.payload;
      // 用find从数组中匹配对应id的条目,替代原state.entities[id]的错误写法
      const existingTodo = state.find(todo => todo.id === id);
      if (existingTodo) {
        existingTodo.name = name;
        existingTodo.description = description;
      }
    }
    
  • 组件层增加取值兜底
    在EditTodo组件中,通过useSelector提取目标Todo时,对未匹配到的场景做兜底处理,避免读取undefined的属性:
    // 示例:以待编辑的目标todoId为匹配条件,未匹配到时返回空对象兜底
    const todo = useSelector(state => 
      state.todo.find(item => item.id === targetEditId) ?? {}
    );
    // 同步初始化useState的编辑值,对name字段做空值兜底
    const [editName, setEditName] = useState(todo.name ?? '');
    
  • 校验action参数对齐
    触发todoUpdated action时,保证payload包含id、name、description三个字段,与reducer解构的参数完全对应,避免漏传字段导致更新失效。

内容的提问来源于stack exchange,提问作者sultan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.04 06:36:05