Saturday 2 November 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

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...