开发者问题收集

Javascript 错误:历史总是落后一步

2021-03-01
52

我正在构建一个类似于 React 官方教程中使用的井字游戏。我正在使用这些方法来处理点击并检查是否有人获胜。现在我的历史记录总是落后一步,我不知道为什么。直到我再移动一步,它才会说我赢了。

  function didSomeoneWin(){
    const squares = history[history.length - 1].squares;
    console.log("history: ", history, " squares: ", squares);
    const lines = [
      [0,1,2],
      [3,4,5],
      [6,7,8],
      [0,3,6],
      [1,4,7],
      [2,5,8],
      [0,4,8],
      [6,4,2],
    ];
    lines.forEach((line) => {
      const [a,b,c] = line;
      if (squares[a] && squares[a] === squares[b] && squares[b] === squares[c]){
        console.log("SOMEONE WON!");
        setWinner( squares[a]); // return the winner: X or O
      }
    })
  }

  function squareClick(i){
    if (!winner){
      const current = history[history.length - 1];
      const squares = current.squares.slice();
      if (squares[i]){
        return;
      }
      squares[i] = turnCount;
      console.log(i);
      console.log("history before: ", history[history.length - 1]);
      setHistory(history.concat([{ squares: squares }]));
      console.log("history after: ", history[history.length - 1]);
      setTurnCount(history.length % 2 === 0 ? "X" : "O");   
      didSomeoneWin();
    }
  }

感谢您的帮助。 在此处输入图片描述

1个回答

在 React 中设置状态始终是异步的。这意味着 history 直到下一次渲染才会更新。

您要么将 squares 传递到 didSomeoneWin 并使用它来确定获胜者:

function squareClick(i){
  // code
  didSomeoneWin(squares)
}
function didSomeoneWin(squares) {
 // remove line fetching squares from history
 // code
}

或者对 didSomeoneWin 的调用应该发生在每次渲染后运行的 useEffect 中:

useEffect(() => { didSomeoneWin(); }, [history]);
// and add history as the dependency, so we only run `didSomeoneWin` if history changes
coagmano
2021-03-01