I am getting the following error
Uncaught TypeError: Cannot read property \'setState\' of undefined
even after binding delta in
In ES7+ (ES2016) you can use the experimental function bind syntax operator ::
to bind. It is a syntactic sugar and will do the same as Davin Tryon's answer.
You can then rewrite this.delta = this.delta.bind(this);
to this.delta = ::this.delta;
For ES6+ (ES2015) you can also use the ES6+ arrow function (=>
) to be able to use this
.
delta = () => {
this.setState({
count : this.state.count + 1
});
}
Why ? From the Mozilla doc :
Until arrow functions, every new function defined its own this value [...]. This proved to be annoying with an object-oriented style of programming.
Arrow functions capture the this value of the enclosing context [...]