ReactJs -TimeTravel - FB教程 - jumpTo 中的 setState 如何工作



以下代码位于FB的reactjs教程的时间旅行部分:

 jumpTo(step) {
    this.setState({
      stepNumber: step,
      xIsNext: (step % 2) === 0,
    });
  }

this.setState在此代码中究竟如何工作?IMO,它创建Game当前状态的不可变副本,并将stepNumberxIsNext属性合并到其中。这究竟是如何实现时间旅行的? 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();