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

React调用.map渲染JSX组件时报Cannot read property 'map' of undefined错误

问题修复方案

1. 核心报错原因:removeThought函数未返回过滤后的数组

你在Dashboard.js的removeThought方法中使用setState更新器回调时,加了花括号但没有返回过滤结果,导致thoughts状态被赋值为undefined,后续调用.map方法自然触发报错:

// 错误写法
setThoughts((prev) => {
    prev.filter((thought) => thought.id !== thoughtID)
});

修复方案二选一:

  • 去掉花括号使用隐式返回:
setThoughts((prev) => prev.filter((thought) => thought.id !== thoughtID));
  • 花括号内添加显式return:
setThoughts((prev) => {
    return prev.filter((thought) => thought.id !== thoughtID)
});

2. 次要问题:过期时间字段名不统一

三个文件的过期时间字段名不一致,会导致自动删除逻辑失效:

  • Dashboard初始化时用的字段是expires
  • Form提交新thought时用的字段是expiresAt
  • Thought组件里读取的字段是expirationTime
    修复方案:统一所有位置的字段名,例如全部改为expiresAt:
  1. 修改Dashboard初始化状态的字段:
const [thoughts, setThoughts] = useState([
    {
    id: generateId(),
    text: "Add your thoughts, don't be shy!",
    expiresAt: expirationTime(),
    }, 
    {
    id: generateId(),
    text: 'They disappear after 15 seconds!',
    expiresAt: expirationTime(), 
    }
]);
  1. 修改Thought组件useEffect的读取字段:
const timeRemaining = thought.expiresAt - Date.now();

完成以上两处修改即可解决map报错和自动过期失效问题。

内容的提问来源于stack exchange,提问作者Gian Paulo Zamora

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 04:15:06