setInterval function without arrow function

后端 未结 7 689
盖世英雄少女心
盖世英雄少女心 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 07:53

    setInterval takes function as first argument, in the second case it is getting a returned value

    Change it to

    this.timerID = setInterval(this.tick.bind(this), 1000);
    

    or

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

    which is probably what you need when you want to bind the function to the React context.

    See this answer on why you need to bind functions in React

    If you don't you could have simply written

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

提交回复
热议问题