Cannot read properties of undefined (reading 'map') at renderList (app.js:42). 请...
错误信息
TypeError: Cannot read properties of undefined (reading 'map') at renderList (app.js:42). 请给出修复示例代码。
AI 解决方案
🔍 错误翻译
原文:TypeError: Cannot read properties of undefined (reading 'map') at renderList (app.js:42)
译文:TypeError:无法读取未定义(undefined)的属性(读取'map'),发生在 renderList 函数(app.js:42行)
🎯 原因分析
undefined值上调用数组方法map(),说明renderList函数中被操作的变量未正确赋值或未初始化。app.js文件的第42行,renderList函数内部。undefined,直接调用map()触发错误。💡 解决方案
// 假设原错误代码:list.map(item => ...) 且 list 为 undefined
// 修复后代码(添加空值判断+默认值)
function renderList(data) {
// 核心修复:给 data 设置默认空数组,避免 undefined 调用 map
const list = data || [];
if (list.length === 0) {
return <div>暂无数据</div>;
}
return (
<ul>
{list.map(item => (
<li key={item.id}>{item.name}</li>
))}
</ul>
);
}
// 调用时确保传递有效参数(若从接口获取,需在数据加载后再调用)
// 示例:接口数据加载后调用
fetchData().then(res => {
// res.data 可能为 undefined,需进一步处理
renderList(res.data || []);
});
🛡️ 预防措施
undefined或null的变量,调用数组方法前先通过空值合并(||)或可选链(?.)校验,例如:data?.map()或(data || []).map()。[]、对象用{}),避免依赖外部数据源赋值后的默认状态。