First, I bind h1 to a click event, call this.changeWeather, and print the value of this.state.isHot
When I click on H1, the console gets the following error
State undefined so I’ll print this and it’s undefined why is that? Let’s start with a piece of code
We will first create a new Person class and print this 1 in the class’s study() method. Instantiate the Person class and call study() 2 from p1.
We can see that when we call the study method through P1 this refers to the Person instance but when we call x() we get undefined if you like
Function (){} can only be called with xxx.study(), and this in function(){} refers to Person only when called from an instance of the class
But when x also refers to function(){}, the call to x() is a direct call. In this case, function(){} will refer to Windows and be undefined in strict mode
In the same way, onclick={this.changeweather}, when you click onclick to find the changeWeather() method, it is a direct call, so the “this” inside is not pointing to Weacher but to Windows. State undefined is used because methods in a class turn on local strict mode
The usual solution is to make this point to Weather inside the changeWeather() method that onClick receives
Constructor = this.changeWeather = this.changeweather ().bind(this); This points to the changeWeather() method for Weather
That will do