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:
- [Solved] vue.esm.js?efeb:591 [Vue warn]: Error in event handler for “click“: “TypeError: Cannot read property
- [Solved] react-router-dom Error: index.js:1 Warning: Functions are not valid as a React child.
- [Solved] React Error: ReactDOM.render is no longer supported in React 18.
- [Solved] React Invariant Violation: Minified React error #130
- [Solved] React Dependency Error: Invalid tag name “^np.0.2“ of package “react@^np.0.2“: Tags may not have an
- [Solved] Vuex state Error: [vuex] do not mutate vuex store state outside mutation handlers.
- React error boundary (What You Should Know & How to Solve)
- Anti card limited Drag Based on react draggable drag
- How to Solve React devtools plug-in Error
- React: How to Solve Web3 import error
- Vue element component V-for error [How to Modify)
- [Solved] Failed to load config “react-app“ to extend from.
- How to React page to achieve entry and exit animation
- [Solved] react-quill failed to install error: Could not resolve dependency
- [Solved] react-router-dom Error: <NavLink>activeClassName
- [Solved] Custom components with click events do not work
- Vue solves the problem of repeated click navigation route error
- React native android: How to Upload Formdata
- [Solved] react Chrome Browser Error: Uncaught TypeError: Cannot read properties of undefined (reading ‘forEach‘)
- [Solved] vant-weapp ui SwipeCell Error: Ignored attempt to cancel a touchmove event with cancelable=false…