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;
我們把num初始值通過構造函數constructor保存在this.state裏,之後我們給button按鈕一個點擊事件handleClick,
然後通過點擊button按鈕來更新num的初始值,當我們點擊的時候,毫無疑問報錯了“Cannot read property 'setState' of undefined”,
翻譯意思是:‘無法讀取未定義的屬性'setState'’,他的意思就是告訴我們,當我們點擊的時候,並沒有讀取到setState中的值,也就是說:
handleClick方法中的this與組件中的this不一致,不是同一個this。
碰到這個問題有兩種解決方法:這兩種方法的目的就是要保證:handleClick方法中的this與組件中的this要保持一致,這樣才能讀取到setState中的值來改變num,
第一種方法:
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); //把組件中的this綁定到handleClick方法中,這樣就會保持this一致
};
handleClick(){
this.setState({
num: this.state.num + 1
})
};
render() {
return (
<div className="App">
{this.state.num}
<button onClick={this.handleClick}>點擊</button><button onClick={this.handleClick.bind(this)}>點擊</button> //把上面的寫到這裏也是可以的
</div>
);
}
}export default App;
第二中方法:
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}>點擊</button><button onClick={()=> {this.handleClick()}>點擊</button>或 <button onClick={() => this.handleClick()}>點擊</button>
</div>
);
}
}export default App;
在 React 裏面,要將類的原型方法通過 props 傳給子組件,傳統寫法需要 bind(this),否則方法執行時 this 會找不到:
<button onClick={this.handleClick.bind(this)}></button>
或者<button onClick={() => this.handleClick()}></button>