React嵌套for循环报未初始化变量错误且仅生成1个Cell如何解决
React批量生成规则命名Cell组件的实现方案
现有代码的问题
- 嵌套for循环内直接调用
return,函数会在第一次内层循环执行到return语句时直接终止运行,只会返回第一个a0对应的Cell组件,无法遍历生成所有40个组件 - 没有收集所有生成的Cell组件实例,React渲染动态列表需要返回合法的JSX数组,单个返回值自然只能渲染一个组件
- 缺少列表项必填的
key属性,且变量声明在循环外作用域,容易引发变量未初始化的报错
正确实现
写法1:基于原有for循环修改
const mapItems = () => { const playerId = ["a", "b", "c", "d"]; // 初始化数组存储所有Cell组件 const cellList = []; for (let j = 0; j < playerId.length; j++) { for (let l = 0; l < 10; l++) { const cellId = playerId[j] + l; cellList.push( <Cell title={cellId} className="column" key={cellId}> {returnItemsForCell(cellId)} </Cell> ); } } // 最后返回完整的组件数组 return cellList; };
写法2:函数式简化写法
使用flatMap替代嵌套循环,代码更简洁易维护:
const mapItems = () => { const playerId = ["a", "b", "c", "d"]; return playerId.flatMap(prefix => Array.from({ length: 10 }, (_, index) => { const cellId = `${prefix}${index}`; return ( <Cell title={cellId} className="column" key={cellId}> {returnItemsForCell(cellId)} </Cell> ); }) ); };
两种写法均会生成按a0-a9、b0-b9、c0-c9、d0-d9顺序排列的40个Cell组件,符合命名规则要求。
内容的提问来源于stack exchange,提问作者Vlad Halyts
相关产品推荐
相关产品推荐

