setInterval function without arrow function

后端 未结 7 696
盖世英雄少女心
盖世英雄少女心 2021-01-02 07:20

I am learning about react components following the documentation https://facebook.github.io/react/docs/state-and-lifecycle.html

Why do we need to use arrow function

7条回答
  •  借酒劲吻你
    2021-01-02 08:04

    The simple answer to that is that the tick function needs to be able access the context of its use/ this, which is the Clock component. In other words it needs to be bound to the Clock component so that it works in the context of the Clock component and not the global context which is everything outside of the Clock component.

    Functions within React classes are not bound by default and failure to bind the function will return undefined instead of the expected result.

    There are several ways to bind the tick function to the Clock component example from the Reactjs website.

    1. Arrow functions can access this which is why they are used in the example. In other words, writing an arrow function implicitly means it binds its contents to the local context (the Clock component in this case). Read more on that in this Medium article

    2. Bind the tick function in the constructor

    class Clock extends React.Component{
     constructor(props){
       super(props);
       this.state={date: new Date()}
       this.tick=this.tick.bind(this)
     }
    
    1. Bind the tick function in the setInterval method
     componentDidMount() {
        this.timerID = setInterval(this.tick.bind(this),
          1000
        );
      }
    

提交回复
热议问题