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:
- 修改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(), } ]);
- 修改Thought组件useEffect的读取字段:
const timeRemaining = thought.expiresAt - Date.now();
完成以上两处修改即可解决map报错和自动过期失效问题。
内容的提问来源于stack exchange,提问作者Gian Paulo Zamora
相关产品推荐
相关产品推荐

