我一直在尝试遵循react tac toe教程,但使用功能组件而不是对象组件。一切都运行得很好,直到回溯部分。
我已经把问题缩小到这样一个事实:在我的handleClick
函数中,setHistory(hist)
实际上并没有改变历史的状态。hist
是数组的数组
(为了简洁起见,我只包含游戏组件,但如果需要整个文件,请告诉我。)
const Game= () => {
const [xIsNext, setXIsNext] = useState(true);
const [history, setHistory] = useState(Array(Array(9).fill(null)));
const [stepNumber, setStepNumber] = useState(0);
function handleClick(i) {
const hist = history.slice(0, stepNumber+1);
console.log(hist)
setHistory(hist);
console.log("in handleClick - log 1 - history size = "+ history.length)
const currentBoard = [...history[stepNumber]];
const winner = calculateWinner(currentBoard);
if (winner || currentBoard[i]) return;
currentBoard[i] = xIsNext ? "X" : "O";
setHistory(history.concat([currentBoard]));
setStepNumber (stepNumber + 1)
setXIsNext(!xIsNext);
}
function jumpTo(move) {
setXIsNext(move % 2 == 0)
setStepNumber(move)
}
const currentBoard = [...history[stepNumber]];
const winner = calculateWinner(currentBoard);
const moves = history.map((step, move) => {
const description = move ?
' Go to move #' + move :
' Go to game start';
return (
<li key={move}>
<button onClick={() => jumpTo(move)} > {description} </button>
</li>
);
})
let status;
if (winner) {
status = winner + " WON !!!!";
}
else {
status = 'Next player: ' + (xIsNext ? "X" : "O");
}
return (
<div className="game">
<div className="game-board">
<Board
squares = {currentBoard}
handleClick={handleClick}
/>
</div>
<div className="game-info">
<div className="status">{status}</div>
<ol>{moves}</ol>
</div>
</div>
)
}
状态在react钩子中不会立即更新。
,
const [counter, setCounter]=useState(0);
handleClick(){
//counter = 0
setCounter(counter + 1);
console.log(counter); //counter is old state so it is still 0
}
对于您的问题:(history
代替hist
)
function handleClick(i) {
const hist = history.slice(0, stepNumber+1);
const currentBoard = [...history[stepNumber]];
const winner = calculateWinner(currentBoard);
if (winner || currentBoard[i])
{
setHistory(hist);
return;
};
currentBoard[i] = xIsNext ? "X" : "O";
setHistory(hist.concat([currentBoard]));
setStepNumber (stepNumber + 1)
setXIsNext(!xIsNext);
}