<分区>
我正在关注 React 网站上的一些教程,并尝试了一些示例代码。这是 codepen 中该代码的链接
https://codepen.io/gaearon/pen/gWWZgR?editors=0010
handleClick(i) {
const history = this.state.history.slice(0, this.state.stepNumber + 1);
const current = history[history.length - 1];
const squares = current.squares.slice();
if (calculateWinner(squares) || squares[i]) {
return;
}
squares[i] = this.state.xIsNext ? "X" : "O";
this.setState({
history: history.concat([{
squares: squares,
}]),
stepNumber: history.length,
xIsNext: !this.state.xIsNext,
});
console.log(this.state.history);
}
render() {
console.log(this.state.history);
const history = this.state.history;
const current = history[this.state.stepNumber];
const winner = calculateWinner(current.squares);
const moves = history.map((val, index) => {
const desc = index ? 'Go to move #' + index : 'Go to game start';
return (
<li key={index}>
<button onClick={() => this.jumpTo(index)}>{desc}</button>
</li>
);
});
let status;
if (winner) {
status = 'Winner: ' + winner;
} else {
status = 'Next player: ' + (this.state.xIsNext ? 'X' : 'O');
}
return (
<div className="game">
<div className="game-board">
<Board
squares={current.squares}
onClick={(i) => this.handleClick(i)}
/>
</div>
<div className="game-info">
<div>{status}</div>
<ol>{moves}</ol>
</div>
</div>
);
}
我的问题是
console.log
在 handleClick 方法和
console.log
在 render 方法中显示了 2 个不同的答案。但它们应该显示出与我理解的相同,因为 handleClick 的 console.log 是在设置状态之后。是因为set State需要一些时间吗?或任何其他事情?