React setState inside of a function this is undefined
Use arrow function (() => {}
) which keeps the last scope (this
) as it is .
MyAction: function(){
this.doFetch().then((response) => {
this.setState({
the_message: response.message
});
});
},
Your inner promise resolution function won't have this
context. One way to fix it:
MyAction: function(){
this.doFetch().then(function(response){
this.setState({
the_message: response.message
});
}.bind(this))
},
Read more about that on this StackOverflow question.
A simple .bind(this)
would solve the issue:
render: function() {
return (
<div>
<div>{this.props.title}</div><br></br>
<div>{this.props.price}</div><br></br>
<div onClick={this.MyAction.bind(this)}>{this.props.qty}</div>
</div>
);
By adding .bind(this)
you keep the scope within your function.