React Hooks重置状态的问题



我正在尝试使用React开发一款井字游戏,并且我被困在基本步骤中,即我希望第一步是X,并将下一个翻转为O,等等。

我有下面的代码。因此,我尝试初始化state & data&;(要设置的)初始值为X,然后设置状态"nextchoice";通过:

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

现在,问题似乎是Square组件再次被重新安装,然后是"firstMove"state每次都被设为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

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

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

问题太多了…

最主要的是游戏状态是存储在方块中,而不是应用组件中。