使用间隔更新计时器的状态

时间:2017-11-30 09:31:43

标签: javascript reactjs

我开始学习React,在首页的例子中,展示了如何创建一个简单的计时器组件:

class Timer extends React.Component {
  constructor(props) {
    super(props);
    this.state = { seconds: 0 };
  }

  tick() {
    this.setState(prevState => ({
      seconds: prevState.seconds + 1
    }));
  }

  componentDidMount() {
    this.interval = setInterval(() => this.tick(), 1000);
  }

  componentWillUnmount() {
    clearInterval(this.interval);
  }

  render() {
    return (
      <div>
        Seconds: {this.state.seconds}
      </div>
    );
  }
}

ReactDOM.render(<Timer />, mountNode);

一切都很清楚,除了这一行(componentDidMount方法):

this.interval = setInterval(() => this.tick(), 1000);

为什么我不能直接写:

this.interval = setInterval(this.tick, 1000);

我收到以下错误:

TypeError: this.setState is not a function

2 个答案:

答案 0 :(得分:1)

constructor方法中,您必须将上下文绑定到tick方法:

constructor(props) {
  super(props);
  this.state = { seconds: 0 };
  this.tick = this.tick.bind(this);
}

答案 1 :(得分:0)