我开始学习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

最佳答案

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

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

09-25 18:15