React JS中如何迭代对象数组内嵌套数组?解决testData不可迭代报错
问题原因分析
1. testData 可能为 undefined
当 details、details[0] 或 one 任意一个不存在时,details?.[0]?.one?.map() 会返回 undefined。而扩展运算符 ... 只能作用于可迭代对象(比如数组),对 undefined 使用扩展运算符就会抛出 testData is not iterable 错误。
2. 数组中混入无效布尔值
isVisible && { label: 'second', value: 'secondValue' } 这行代码,当 isVisible 为 false 时,会将 false 直接加入 myData 数组。后续遍历数组时,false 不是 Item 类型,访问 item?.label 会引发额外错误。
3. 语法错误(次要)
return 中的 map 方法缺少闭合的括号 ),会导致语法解析失败。
修正后的代码方案
const testData = details?.[0]?.one?.map((item) => { const labelTwo = item?.itemType === 'FIRST' ? 'newLabel' : 'oldLabel'; return { label: details?.[0]?.one?.length > 1 ? labelTwo : 'labelOne', value: item?.value, }; }) ?? []; // 给testData设置默认空数组,避免undefined const myData: Item[] = [ ...testData, { label: 'first', value: 'firstValue', }, // 用扩展语法避免混入布尔值 ...(isVisible ? [{ label: 'second', value: 'secondValue' }] : []), ]; return ( <> {myData?.map((item: Item) => { return ( <div> <div>{item?.label}</div> <div>{item?.value}</div> </div> ); })} {/* 补上map的闭合括号 */} </> );
关键修正点说明
- 使用
?? []给testData设置默认空数组,确保无论可选链是否生效,testData都是可迭代的数组类型。 - 用扩展语法
...(isVisible ? [...] : [])替代布尔短路表达式,只有当isVisible为true时才添加目标对象,避免数组中混入false。 - 修复
map方法的语法错误,补上闭合括号。
内容的提问来源于stack exchange,提问作者Anurag Mishra
相关产品推荐
相关产品推荐

