【问题标题】:Too many re-renders on setting state设置状态的重新渲染过多
【发布时间】:2021-09-21 02:02:37
【问题描述】:

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

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


    【解决方案1】:

    您应该将修改状态的函数调用放在 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。从而创建一个无限循环。

    【讨论】:

    • 嘿,这真是一种享受!我从没想过解决方案是调用函数的行。谢谢。
    猜你喜欢
    • 2023-02-09
    • 2020-11-01
    • 1970-01-01
    • 2019-09-16
    • 2023-03-09
    • 2021-06-11
    • 2020-09-12
    • 1970-01-01
    • 2019-11-09
    相关资源
    最近更新 更多