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

React中使用.map()遍历grid时出现变量未定义报错如何解决?

报错核心原因与修复点

    1. render内未正确读取state中的grid:class组件中存储在state内的变量必须通过this.state.grid访问,你直接写grid.map相当于读取当前作用域下未声明的变量,自然报未定义。
    1. map回调无返回值:你使用大括号包裹map的回调逻辑却没有写return语句,即便grid能访问也渲染不出任何节点,可改为小括号做隐式返回或显式加return。
    1. 二维数组未完成两层遍历:你生成的grid是15行50列的二维数组,仅对第一层做遍历只能拿到每行的数组,需要嵌套一层map遍历每行列元素才能渲染单个网格节点。
    1. createGrid未存入格子属性:当前push为空,后续无法定位每个格子的行列坐标,可存入包含row、col属性的对象方便后续操作。

修复后完整代码

import { Component } from 'react';

class PathfinderGrid extends Component {
  constructor(props) {
    super(props)
    this.state = {
      grid: [],
    };
  }
  
  componentDidMount() {
    const grid = createGrid();
    this.setState({ grid });
  }

  render() {
    // 从state中解构取出grid
    const { grid } = this.state;
    return (
      <div>
        {/* 第一层遍历所有行 */}
        {grid.map((row, rowIndex) => (
          <div key={rowIndex} style={{ display: 'flex' }}>
            {/* 第二层遍历每行内的所有列格子 */}
            {row.map((cell, colIndex) => (
              <div 
                key={colIndex}
                style={{ width: '20px', height: '20px', border: '1px solid #ccc' }}
              >
                {/* 此处可根据需求展示格子属性,比如行列号 */}
                {/* {cell.row}-{cell.col} */}
              </div>
            ))}
          </div>
        ))}
      </div>
    );
  }
}

const createGrid = () => {
  let grid = [];
  for (let row = 0; row < 15; row++) {
    let currentRow = [];
    for (let col = 0; col < 50; col++) {
      // 存入格子基础属性,方便后续做路径查找、障碍物标记等操作
      currentRow.push({ row, col, isWall: false, isVisited: false });
    }
    grid.push(currentRow);
  }
  return grid;
};

export default PathfinderGrid;

内容的提问来源于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 16:27:01