问题
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 here:
this.timerID = setInterval(() => this.tick(), 1000);
Why can't I just say (obviously it doesn't work)
this.timerID = setInterval(this.tick(), 1000);
回答1:
The first argument for setInterval
is of type function
. If you write this:
this.timerID = setInterval(this.tick(), 1000);
…then you don't pass a function, instead you execute the function this.tick
immediately and then pass the value returned by that function call as an argument.
You could write it like this:
this.timerID = setInterval(this.tick, 1000);
If you omit the parentheses, you pass a reference to your this.tick
function, which is then executed by setInterval
after 1000 milliseconds.
回答2:
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);
回答3:
You need to supply a function reference, you are trying to invoke a function, unless that function returns a function reference, your code will not work
It should look like so
this.tick = function() { .... }
this.timerID = setInterval(this.tick, 1000);
回答4:
If you are not using arrow function then your code should look something like this:
this.timerID = setInterval(function(){ this.tick() }, 1000);
回答5:
Technically, you should be able to use the second code snippet if this.tick()
returns a function.
来源:https://stackoverflow.com/questions/45780551/setinterval-function-without-arrow-function