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

React-Redux渲染UI时报错:Cannot read properties of undefined (reading 'name')

React-Redux 中 "Cannot read properties of undefined (reading 'name')" 错误排查与解决

错误原因

  1. Reducer 与 Action 数据不匹配:

    • 在 index.js 的 Reducer 中,处理 ADD 动作时,代码尝试将 action.name 添加到状态数组,但实际上 App.js 中 dispatch 的 Action 对象里并没有 name 字段,而是用 item 存储了包含 id、name、price 的对象。
    • 这导致每次执行 ADD 动作时,都会向状态数组中添加 undefined,后续渲染时遍历数组,访问 i.name 自然会抛出“读取 undefined 的 name 属性”的错误。
  2. 初始渲染无问题,但添加数据后状态异常:

    • 初始状态是空数组,map 方法不会执行,所以首次渲染不报错;但点击添加按钮后,状态数组中混入了 undefined,遍历操作就会触发错误。

解决方法

修正 Reducer 中读取 Action 数据的逻辑,将 action.name 改为 action.item,确保状态数组中存储的是完整的商品对象:

修改 index.js 中的 Reducer 代码:

const store = createStore((state = [], action) => {
  if (action.type === 'ADD') return [...state, action.item]; // 替换 action.name 为 action.item
  return state;
});

验证修改

修改后,点击添加按钮时,Reducer 会正确将包含 id、name、price 的 item 对象存入状态数组,App 组件遍历 props.items 时,每个 i 都是有效的对象,访问 i.name 和 i.price 不会再触发错误。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 13:17:26