javascript – 确保React状态已更新为游戏循环

我在React写了一个版本的Conway的生命游戏.组件的状态包含描述当前时间哪些单元处于活动状态的网格.在每个游戏循环中,计算新网格并使用下一次迭代更新状态.

我发现,由于setState是异步的,当使用setInterval重复调用iterate函数时,我不保证每次迭代运行时都使用当前版本的网格.

是否有在React中使用setInterval的替代方法可以避免由setState异步引起的任何潜在问题?

以下是描述游戏循环的相关函数:

  go = () => {
    const { tickInterval } = this.state;
    this.timerId = setInterval(this.iterate, 570 - tickInterval);
    this.setState({
      running: true,
    });
  };

  iterate = () => {
    const { grid, gridSize, ticks } = this.state;
    const nextGrid = getNextIteration(grid, gridSize);
    this.setState({
      grid: nextGrid,
      ticks: ticks + 1,
    });
  };

最佳答案 如果需要根据当前状态设置状态,直接依赖this.state是错误的,因为它可能是异步更新的.您需要做的是将函数传递给setState而不是对象:

this.setState((state, props) => ({
  // updated state
}));

在你的情况下,它将是这样的:

iterate = () => {

  this.setState(state => {
    const { grid, gridSize, ticks } = state;
    const nextGrid = getNextIteration(grid, gridSize);
    return {
      grid: nextGrid,
      ticks: ticks + 1
    }
  });

};
点赞