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

React中使用.map()生成网格时渲染结果不符合预期问题咨询

问题排查及修复方案

存在的问题

  • createGrid 函数内重复插入行数据:循环体内连续两次执行 grid.push(currentRow),会导致最终生成的网格行数是预期的2倍,属于冗余逻辑。
  • 渲染逻辑缺失列遍历:render 方法中仅遍历了 grid 的行维度,每一行对应的列数组没有做二次遍历,导致每行仅渲染1个单元格,而非预期的50个单元格。
  • Node 组件未传入必要属性:渲染单元格时没有将行、列对应的节点数据传递给 Node 组件,组件无法拿到对应信息完成样式/内容渲染。
  • 存在无效代码:createNode 函数中 return 语句后的两个 console.log 永远不会执行,属于死代码。

修复后的代码

修复createGrid相关函数

const createGrid = () => {
  const grid = [];
  for (let row = 0; row < 15; row++) {
    const currentRow = [];
    for (let col = 0; col < 50; col++) {
      currentRow.push(createNode(row, col));
    }
    // 移除重复的push语句,只保留一次
    grid.push(currentRow);
  }
  return grid;
};

const createNode = (row, col) => {
  // 移除return后的无效console.log
  return {
    row,
    col,
  };
};

修复render渲染逻辑

render() {
  return (
    <div>
      {/* 遍历行,给每行加flex容器实现横向排列单元格 */}
      {this.state.grid.map((row, rowIdx) => (
        <div key={rowIdx} style={{ display: 'flex' }}>
          {/* 二次遍历当前行的所有列,渲染每个单元格 */}
          {row.map((node, colIdx) => (
            <Node key={colIdx} node={node} />
          ))}
        </div>
      ))}
    </div>
  );
}

额外注意点

  • 建议给列表渲染的元素加上唯一key属性,避免React抛出列表渲染警告,也能优化渲染性能。
  • 要实现网格的方块视觉效果,需要给Node组件设置固定的宽高、边框样式,否则单元格不会有可见的视觉表现。

内容的提问来源于stack exchange,提问作者Ben.Clough

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 07:36:03