React.js: “setState” undefined
I use setState();
in custom function, but appear error, thanks Fabien Sa help me to figure out this problem.
Solution: use ()=>
instead of function()
//example
//error
findComment(){
let id = this.props.post._id;
console.log(id);
this.props.comments.forEach(function(e){
if(e.id == id){
this.setState({
singleComment : e.comment,
find: true
});
}
});
}
//correct
findComment(){
let id = this.props.post._id;
console.log(id);
this.props.comments.forEach( (e) =>{
if(e.id == id){
this.setState({
singleComment : e.comment,
find: true
});
}
});
}