[Solved] React Click the Event to Modify the State Value Error

React Click the Event to Modify the State Value Error

Make a mistake.

Cannot read properties of undefined (reading ‘setstate’) when updating the state value

import React from "react";
class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      text: "Hello",
    };
    //Modify the codes behind this line
    
    //Modify the codes before this line
  }
  handleClick() {
    this.setState({
      text: "You clicked!",
    });
  }

  render() {
    return (
      <div>
        {/* Modify the codes behind this line */}
        <button onClick={this.handleClick}>Click Me</button>
        {/* Modify the codes before this line */}
        <h1>{this.state.text}</h1>
      </div>
    );
  }
}
export default MyComponent;

An error is reported when updating the state value,

Cannot read properties of undefined (reading ‘setState’)

It seems that the direction of this needs to be changed. I don’t quite understand it.

    // Modify the codes behind this line
    this.handleClick = this.handleClick.bind(this);
    // Modify the codes before this line

Value update after clicking

Another method is to modify it into an arrow function

  handleClick = () => {
    this.setState({
      text: "You clicked!",
    });
  };

The modified value can still be realized

Read More: