1狀態更新可能是異步的
this.props 和 this.state 可能是異步更新的,你不應該依靠它們的值來計算下一個狀態。
// Wrong
this.setState({
counter: this.state.counter + this.props.increment,
});
//corret
this.setState((prevState, props) => ({
counter: prevState.counter + props.increment
}));
2 this中保存字段
雖然 this.props 由React本身設置以及this.state 具有特殊的含義,但如果需要存儲不用於視覺輸出的東西,則可以手動向類中添加其他字段。舉個例子:
componentDidMount() {
this.timerID = setInterval(
() => this.tick(),
1000
);
}
componentWillUnmount() {
clearInterval(this.timerID);
}
比如,我在componentDidMount()中定義的計時器的變量需要在另一個函數componentWillUnmount能使用,這時候,我們可以把在多個函數都需要的變量存在this中,這樣就可以在多個不同的函數中訪問到同一個變量。
3.阻止默認事件
React 中另一個不同是你不能使用返回 false 的方式阻止默認行爲。你必須明確的使用 preventDefault。
4.謹慎對待回調函數中的this
你必須謹慎對待 JSX 回調函數中的 this,類的方法默認是不會綁定 this 的。如果你忘記綁定你在類中定義的handleClick方法, 並把它傳入到組件的 onClick, 當你調用這個函數的時候 this 的值會是 undefined,這一點必須要注意。
class Toggle extends React.Component {
handleClick() {
this.setState(prevState => ({
isToggleOn: !prevState.isToggleOn
}));
}
render() {
return (
<button onClick={this.handleClick}>
{this.state.isToggleOn ? 'ON' : 'OFF'}
</button>
);
}
}
}
上面的代碼是有問題的,沒有綁定this,目前可以使用三種方法解決:
- 手動在constructor函數中添加this綁定: this.handleClick = this.handleClick.bind(this);
- 使用箭頭函數 <button onClick={() => this.handleClick()}>
- 直接把handleClick使用箭頭函數的語法實現