Using setInterval in React Component

前端 未结 3 1514
一生所求
一生所求 2020-12-06 13:18

I was reading the tutorial on the official react website. In the example about life cycle methods, under the componentDidMount method, a timerID is set to the setInterval fu

3条回答
  •  半阙折子戏
    2020-12-06 13:47

    this.timerID is a numeric, non-zero value which identifies the timer created by the call to setInterval(); this value can be passed to clearInterval to clear the timer.

    So when calling the setInterval in componentDidMount like

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

    you want to execute the tick() function every 1 sec after the component has mounted. Now when you navigate to another component and your current component has unmounted, if you do not clear the interval call to tick() function, it will continue to be executed.

    Hence in the componentWillUnmount function you timer is cleared which is identified by the numeric value returned by setInterval which is stored in this.timerID

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

    so the complete code as provided in the React docs is

    class Clock extends React.Component {
      constructor(props) {
        super(props);
        this.state = {date: new Date()};
      }
    
      componentDidMount() {
        this.timerID = setInterval(
          () => this.tick(),
          1000
        );
      }
    
      componentWillUnmount() {
        clearInterval(this.timerID);
      }
    
      tick() {
        this.setState({
          date: new Date()
        });
      }
    
      render() {
        return (
          

    Hello, world!

    It is {this.state.date.toLocaleTimeString()}.

    ); } } ReactDOM.render( , document.getElementById('root') );

提交回复
热议问题