The previous section is standard, but in real development it is too cumbersome, so we need to simplify the code. Previous code:

class Weather extends React.Component {
  constructor(props) {
    super(props);
    this.state = {isHot: true};
    this.changeWeather = this.changeWeather.bind(this);
  }
  render() {
    const { isHot } = this.state;
    return <h1 onClick={this.changeWeather}>The weather is very hot today. 'Hot' : 'cool '}</h1>
  }
  changeWeather() {
    this.setState({isHot:!this.state.isHot})
  }
}
ReactDOM.render(<Weather />.document.getElementById('app'));
Copy the code

We put state in the constructor for that this, can we bring that out? We can’t write let, but we can write assignment, so we can write state = {}. What about functions? Now we have a function on the prototype object of the class, so can we use the assignment statement to write this function out of the class into its own method? Sure, but the “this” problem in the assignment statement is still unresolved. Wait, function, this, this, function, arrow function!! All of a sudden, all of a sudden, the arrow function is pointing to its nearest scope this, so what is this outside the function? Class instances, of course, so our code has been simplified by the changes.

class Weather extends React.Component {


  state = {isHot: true};
  render() {
    const { isHot } = this.state;
    return <h1 onClick={this.changeWeather}>The weather is very hot today. 'Hot' : 'cool '}</h1>
  }
  changeWeather = () = > {
    this.setState({isHot:!this.state.isHot})
  }
}
ReactDOM.render(<Weather />.document.getElementById('app'));
Copy the code