在 React 中进行倒计时

Doing a countdown in React

我正在尝试弄清楚如何在 React 的游戏组件中进行赛前倒计时。我正在尝试这样,但它说 this.countDown 不是一个函数 - 当它被明确定义时。

有人能指出我错在哪里吗?

class Game extends Component {
  constructor() {
    super();

    this.state = {
      timer: 5,
      isHidden: true,
      randomIndex: 0,
      score: 0
    };

    this.countDown = this.countDown.bind(this);
  }

  countDown() {
    this.setState({
      timer: this.state.timer--
    });
  }

  render() {
    const tables = this.props.tables.map(table => {
      return (
        <li key={table.uniqueId}>
          {table.timesTable[0]} X {table.timesTable[1]}
        </li>
      );
    });

    setInterval(function() {
      this.countDown();
      console.log(this.state.timer);
    }, 1000);

    // if (this.state.timer > 0) {
    //     this.countDown();
    // }

    return (
      <div className="Game">
        <h3>Current Tables are:</h3>
        {tables}
        <h1 id="countdown">{this.state.timer}</h1>
        <Question />
        {/* question handles the right or wrong logic, receives a random timestable */}
        <h3>Score: {this.state.score}</h3>
        <button onClick={this.stopGame}>Stop Game</button>
        <button onClick={this.startOver}>Start Over</button>
      </div>
    );
  }
}

export default Game;

在该示例中,setInterval 的回调中的 this 指的是 global window 对象,因为它作为 window.setInterval(...) 执行,所以 this.countDown() 将等于window.countDown(),这显然是不正确的。

要从父级范围获取 this,您可以使用 arrow functions

setInterval(() => {
  this.countDown();
  console.log(this.state.timer)
}, 1000);

或简单地 bind this:

setInterval(function() {
  this.countDown();
  console.log(this.state.timer)
}.bind(this), 1000); // bind this from parent's scope