Learning Redux
上QQ阅读APP看书,第一时间看更新

React life cycle methods

All that's left to do now is to update the state. React calls certain life cycle methods, which can be used to create side effects, such as timers or API requests. In our case, we will use two very commonly used React life cycle methods:

componentDidMount(): This method is called when the component is rendered to the DOM for the first time. Note the difference to constructor(), which is called when the component is created. Creation happens much earlier than the actual rendering. componentDidMount offers a way to do something (creating timers, requests, and so on) when the component first appears.

componentWillUnmount(): This method is called before the DOM produced by the component is removed. It is basically a way to clean up any side effects (timers, unfinished requests, and so on) before the component disappears.

We want to create a timer that triggers every second and calls a this.tick() method, where we are going to update the state:

We are going to use setInterval to create a timer that triggers every second (1000 milliseconds). Because we want this timer to be created when the component first appears (gets mounted), we use componentDidMount():

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

Do not forget to clean up your timer before the component unmounts, via componentWillUnmount():

  componentWillUnmount () {
    clearInterval(this.timer)
  }