App.js
import React, { Component } from 'react'; import './App.css'; class App extends Component { constructor(props){ super(props); this.state = { num: 90 } }; handleClick(){ this.setState({ num: this.state.num + 1 }) }; render() { return ( <div className="App"> {this.state.num} <button onClick={this.handleClick}>点击</button> </div> ); } } export default App;
We save the initial value of num in this. State through the constructor, and then we give the button a click event, handleclick
Then click the button to update the initial value of num. when we click, there is no doubt that “cannot read property ‘set state’ of undefined” is reported
The translation means: “can’t read the undefined property ‘setstate'”, which tells us that when we click, we don’t read the value in the setstate
This in the handleclick method is not the same as this in the component
There are two solutions to this problem: the purpose of these two methods is to ensure that this in the handleclick method is consistent with this in the component, so that the value in the setstate can be read to change num
First method:
import React, { Component } from 'react'; import './App.css'; class App extends Component { constructor(props){ super(props); this.state = { num: 90 } this.handleClick = this.handleClick.bind(this); }; handleClick(){ this.setState({ num: this.state.num + 1 }) }; render() { return ( <div className="App"> {this.state.num} <button onClick={this.handleClick}>click</button> <button onClick={this.handleClick.bind(this)}>click</button> </div> ); } } export default App;
Second translation
import React, { Component } from 'react'; import './App.css'; class App extends Component { constructor(props){ super(props); this.state = { num: 90 } }; handleClick(){ this.setState({ num: this.state.num + 1 }) }; handleClick = () => { this.setState({ num: this.state.num + 1 }) }; render() { return ( <div className="App"> {this.state.num} <button onClick={this.handleClick}>click</button> <button onClick={()=> {this.handleClick()}>click</button> or <button onClick={() => this.handleClick()}>click</button> </div> ); } } export default App;
In react, to transfer the prototype method of a class to the subcomponent through props, the traditional writing method requires bind (this), otherwise this will not be found when the method is executed
<button onClick={this.handleClick.bind(this)}></button>
Or
<button onClick={() => this.handleClick()}></button>