Saturday, February 16, 2019

reactjs - Cannot call this.setState in addEventListener function



enter image description here




I am trying to change the state on the click of a button I created through DOM methods. I tried passing "this" as a variable through the arguments of the function



var self="this"
b.addEventListener("click", function(self){
self.setState({health:100}) })


and also tried adding .bind(this) at the end of the function but no luck.




b.addEventListener("click", function(){
this.setState({health:100}) })

Answer



Please add above event handling in componentDidMount life cycyle.



componentDidMount(){

var self=this;
//add b defination here;


b.addEventListener("click", function()=>{

//remove self from callback.
//self here causing shadowing to above self defination used below

self.setState({health:100}) });

OR


this.setState({health:100}) });

}

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...