I understand you might feel this is a redundant question but hear me out.
I am working with React class components and I just learnt that we need to bind a event handler function in the constructor of the component in order to access this.setState()
inside the event handler. Now from what I understand about JavaScript classes, this
can be accessed by any method inside a class.
To demonstrate what I am saying, here is the code:
class Parent {
setState() {
console.log("Set State is called");
}
}
class Child extends Parent {
eventHandler() {
this.setState();
}
render() {
console.log("Render method called");
console.log("assume an event happened and event handler is called");
this.eventHandler();
}
}
new Child().render()
The output of the above code is:
Render method called
assume an event happened and event handler is called
Set State is called
Contrasting the above code with how react works (i.e. assuming setState
is a method defined in the class React.Component
), why does react throw an error when this.setState()
is called inside an event handler?