首页 > 解决方案 > 设置状态的重新渲染过多

问题描述

我有以下代码导致渲染过多。

const passAcrossSelectedGame = props => {
    if (props.passedGamesFlag === 1) {
      props.setPassedGamesFlag(0);
      gameDetails = {
        blackKingSquare: '',
        whiteKingSquare: '',
        };

      plyViewed = 0;

      setHistory(game.history());

      const auxGame = new Game();

      gameHistory = [];
      gameHistory.push(auxGame.fen());
      game.history().forEach(move => {
        auxGame.move(move);
        fenHistory.push(auxGame.fen());
      });
    }
  };
  passAcrossSelectedGame(props);

我已将违规行确定为 setHistory(game.history());

当我注释掉那条线时,我没有得到不断的重新渲染。但我需要它在那里!什么解决方案可能适合这个?

标签: reactjs

解决方案


您应该将修改状态的函数调用放在 useEffect 挂钩中:

const passAcrossSelectedGame = props => {
    if (props.passedGamesFlag === 1) {
      props.setPassedGamesFlag(0);
      gameDetails = {
        blackKingSquare: '',
        whiteKingSquare: '',
        };

      plyViewed = 0;

      setHistory(game.history());

      const auxGame = new Game();

      gameHistory = [];
      gameHistory.push(auxGame.fen());
      game.history().forEach(move => {
        auxGame.move(move);
        fenHistory.push(auxGame.fen());
      });
    }
};

useEffect(() => {
  passAcrossSelectedGame(props);
}, [props]

您收到此错误是因为 setState 触发了重新渲染,它再次调用了 setState。从而创建一个无限循环。


推荐阅读