Wednesday, November 13, 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

hard drive - Leaving bad sectors in unformatted partition?

Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...