I'm trying to learn React and I don't understand why this does not do anything when I try without an arrow function
componentDidMount() {
var self = this
this.timer = window.setInterval(function () {
self.increment
}, 1000)
}
Is the correct pattern self.increment()?
So why do I need the () when I don't need it in:
componentDidMount() {
this.timer = window.setInterval(this.increment.bind(this),1000)
}
You are not invoking self.increment, you are properly scoping this for your code to work. Maybe it appears it's not working because your interval's callback does not do anything :)
Also, here's a simpler version of your code, you could omit the .bind if your function does not need to access your component's scope, but typically in react you'd want access to that:
this.timer = setInterval(this.increment.bind(this), 1000)