首页 > 解决方案 > 状态重置的 React Hooks 问题

问题描述

我正在尝试使用 React 开发 Tic Tac Toe 游戏并停留在基本步骤,即我希望第一步是 X 并将下一个翻转到 O 等等。

我有下面的代码。因此,我尝试将状态“数据”(要设置的内容)初始化为 X,然后通过以下方式将状态“nextChoice”设置为反向:

nxtChoice = (data === "X") ? "O" : "X";
setNextChoice(nxtChoice);

现在,问题似乎是 Square 组件再次重​​新安装,然后每次导致问题时“firstMove”状态都设置为 true,即无法在 X 和 O 之间翻转。

上面代码的逻辑问题是什么,我怎么不能每次都重置 firstMove?

function Square(props) {
  const [firstMove, setFirstMove] = useState(true);
  let [nextChoice, setNextChoice] = React.useState("X");
  let [data, setData] = React.useState("");

  useEffect(() => {
    if (data !== "") {
      nxtChoice = (data === "X") ? "O" : "X";
      setNextChoice(nxtChoice);
    }
  }, [data]);

  const squareClicked = () => {
    let nxtChoice = firstMove ? "X" : nextChoice;
    setData(nxtChoice);
    setFirstMove(false);
  };

  return (
    <div className="square" style={squareStyle} onClick={squareClicked}>
      {data}
    </div>
  );
}

class Board extends React.Component {
  render() {
    return (
      <div style={containerStyle} className="gameBoard">
        <div id="statusArea" className="status" style={instructionsStyle}>
          Next player: <span>X</span>
        </div>
        <div id="winnerArea" className="winner" style={instructionsStyle}>
          Winner: <span>None</span>
        </div>
        <button style={buttonStyle}>Reset</button>
        <div style={boardStyle}>
          <div className="board-row" style={rowStyle}>
            <Square row={"1"} column={"1"} />
            <Square row={"1"} column={"2"} />
            <Square row={"1"} column={"3"} />
          </div>
          <div className="board-row" style={rowStyle}>
            <Square row={"2"} column={"1"} />
            <Square row={"2"} column={"2"} />
            <Square row={"2"} column={"3"} />
          </div>
          <div className="board-row" style={rowStyle}>
            <Square row={"3"} column={"1"} />
            <Square row={"3"} column={"2"} />
            <Square row={"3"} column={"3"} />
          </div>
        </div>
      </div>
    );
  }
}

代码也可以在 https://codesandbox.io/s/rough-glade-c1ssw?file=/src/App.js:1307-3349上看到

标签: reactjsreact-hooksuse-effect

解决方案


您看到的并不是Square组件被重新安装,而是对于 的每个实例Square,它都有一个单独的单独工作状态。

为了让游戏正常工作,这些状态应该被移动到Board组件并传递给每个Square组件。


推荐阅读