Friday, 13 May 2016

javascript - React - uncaught TypeError: Cannot read property 'setState' of undefined



I am getting the following error




Uncaught TypeError: Cannot read property 'setState' of undefined




even after binding delta in the constructor.



class Counter extends React.Component {
constructor(props) {
super(props);

this.state = {
count : 1
};

this.delta.bind(this);
}

delta() {
this.setState({
count : this.state.count++
});
}

render() {
return (

{this.state.count}




);
}
}

Answer



This is due to this.delta not being bound to this.



In order to bind set this.delta = this.delta.bind(this) in the constructor:



constructor(props) {
super(props);

this.state = {
count : 1
};

this.delta = this.delta.bind(this);
}


Currently, you are calling bind. But bind returns a bound function. You need to set the function to its bound value.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...