reactjs - 状态重置的 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上看到
解决方案
您看到的并不是Square
组件被重新安装,而是对于 的每个实例Square
,它都有一个单独的单独工作状态。
为了让游戏正常工作,这些状态应该被移动到Board
组件并传递给每个Square
组件。
推荐阅读
- mongodb - 如何使用 $cond 在 Golang 中运行 MongoDB 查询
- maven - 使用 antrun maven 插件从插件类路径执行 jar
- python - 添加从 JSON 请求收集的字符串
- apache-spark - 为什么 Spark 广播 1.5GB 表(参见 DAG)?
- swift - SwiftUI 搜索栏无法产生诊断错误
- android-mediarecorder - MediaRecorder.setOutputFile java.io.FileNotFoundException:: open failed: EACCES (Permission denied) on android 9 in android emulator
- reactjs - 反应/打字稿类型'ChangeEvent
' 缺少类型 'KeyboardEvent 的以下属性 - python - 一种每 200 个位置将数据从字符串发送到变量的方法 -For 循环
- java - RecyclerView 中的项目位置仅在拖动列表时发生变化,同时也是错误的
- node.js - TypeError:userDB 不是构造函数