Javascript ×;错误:重新渲染过多。React限制渲染的数量以防止无限循环

Javascript ×;错误:重新渲染过多。React限制渲染的数量以防止无限循环,javascript,reactjs,Javascript,Reactjs,我认为这个错误是因为我在函数中调用setState,但我不确定,也不知道如何修复它 这是为扫雷游戏制作棋盘的众多尝试之一,但我经历了一段艰难的时光,每次我尝试制作二维数组时,都会出现这个错误,这使得棋盘只成为一个数组,所以我将其划分为多个单元格 import React,{useState}来自“React”; 导入“/board.css”; 功能板(道具){ const[cells,setCells]=useState([]); const createBoard=()=>{ let boa

我认为这个错误是因为我在函数中调用setState,但我不确定,也不知道如何修复它

这是为扫雷游戏制作棋盘的众多尝试之一,但我经历了一段艰难的时光,每次我尝试制作二维数组时,都会出现这个错误,这使得棋盘只成为一个数组,所以我将其划分为多个单元格

import React,{useState}来自“React”;
导入“/board.css”;
功能板(道具){
const[cells,setCells]=useState([]);
const createBoard=()=>{
let board=新阵列(道具行);
for(设i=0;i
尝试使用效果挂钩以避免重新渲染。我建议您阅读React网站上的文档。 问题是您直接在render方法中更改状态,更改状态将重新渲染组件,并且您反复更改它,这就是无限循环

useEffect(() => {

  const createBoard = () => {
    let board = new Array(props.rows);
    for (let i = 0; i < board.length; i++) {
      board[i] = new Array(props.columns);
    }

    for (let i = 0; i < props.rows; i++) {
      for (let j = 0; j < props.columns; j++) {
        board[i][j] = {
          isMine: false,
          isOpen: false,
          isFlag: false,
          x: i,
          y: j,
        };
      }
    }

    for (let i = 0; i < props.mines; i++) {
      let randomRow = Math.floor(Math.random() * props.rows);
      let randomColumn = Math.floor(Math.random() * props.columns);
      board[randomRow][randomColumn].isMine = true;
    }

    for (let i = 0; i < props.rows; i++) {
      for (let j = 0; j < props.columns; j++) {
        setCells(cells.concat(board[i][j]));
      }
    }

    return board;
  };

  console.table(createBoard());
}, []);
useffect(()=>{
const createBoard=()=>{
let board=新阵列(道具行);
for(设i=0;i
您遇到了哪一个错误?@olexandroplavskyi重新渲染太多了当我试图运行代码时,它没有崩溃。您使用的是哪个版本的React,请提供错误的屏幕截图。@Puk我使用的是版本16.13.1,我将图片放在了说明中。问题可能实际上存在于您的src/index.js中,因为渲染问题从那里开始。在发布问题时,您提供的上下文越多越好。如果您可以将代码片段粘贴到index.js(错误显示在其中)和App.js中,那就太好了
useEffect(() => {

  const createBoard = () => {
    let board = new Array(props.rows);
    for (let i = 0; i < board.length; i++) {
      board[i] = new Array(props.columns);
    }

    for (let i = 0; i < props.rows; i++) {
      for (let j = 0; j < props.columns; j++) {
        board[i][j] = {
          isMine: false,
          isOpen: false,
          isFlag: false,
          x: i,
          y: j,
        };
      }
    }

    for (let i = 0; i < props.mines; i++) {
      let randomRow = Math.floor(Math.random() * props.rows);
      let randomColumn = Math.floor(Math.random() * props.columns);
      board[randomRow][randomColumn].isMine = true;
    }

    for (let i = 0; i < props.rows; i++) {
      for (let j = 0; j < props.columns; j++) {
        setCells(cells.concat(board[i][j]));
      }
    }

    return board;
  };

  console.table(createBoard());
}, []);