以下代码位于FB的reactjs教程的时间旅行部分:
jumpTo(step) {
this.setState({
stepNumber: step,
xIsNext: (step % 2) === 0,
});
}
this.setState
在此代码中究竟如何工作?IMO,它创建Game
当前状态的不可变副本,并将stepNumber
和xIsNext
属性合并到其中。这究竟是如何实现时间旅行的? jumpTo
不应该在步骤后删除历史记录吗?
这是本教程中最棘手的部分。jumpTo
重置stepNumber
组件的最新状态是正确的Game
正确的。但是render
Game
组件的方法使用stepNumber
作为索引来从历史记录中检索当前squares
。这确实非常聪明。代码摘录如下:
render() {
const history = this.state.history;
const current = history[this.state.stepNumber];
const winner = calculateWinner(current.squares);
因此,对于"在那一步之前jumpTo
不应该砍掉历史吗?"问题的答案是否定的。此外,如果jumpTo
试图修改历史,那么从技术上讲,时间旅行将是不可能的。
还值得注意的是,一旦通过单击板修改历史步骤,该步骤中的所有"未来"历史记录都将失效。因此,切碎历史是用handleClick
方法完成的。Game
组件的handleClick
方法的代码摘录:
handleClick(i) {
const history = this.state.history.slice(0, this.state.stepNumber + 1);
const current = history[history.length - 1];
const squares = current.squares.slice();