針對state要明確三件事:
1.不要直接修改state
// 錯的
this.state.name = 'alice';
應該使用setState()
// 正確
this.setState({
name: 'alice'
});
注意:構造函數是唯一可以給this.state賦值的地方
constructor(props) {
super(props);
this.state = {
name: 'alice'
};
}
2.state的更新可能是異步的
setState()函數是異步的,因此,更新數據時可能會異步更新。所以不要依賴要更新的值去更新下一個狀態。
要解決這個問題,可以讓 setState() 接收一個函數而不是一個對象。
這個函數用上一個 state 作爲第一個參數,將此次更新被應用時的 props 做爲第二個參數:
// 正確
this.setState((state, props) => ({
counter: state.counter + props.increment
}));
3.state的更新會被合併
當調用setState()的時候,React會把提供的對象合併到當前的state。
// Correct
constructor(props) {
super(props);
this.state = {
posts: [],
comments: []
};
}
分開更新
componentDidMount() {
fetchPosts().then(response => {
this.setState({
posts: response.posts
});
});
fetchComments().then(response => {
this.setState({
comments: response.comments
});
});
}
這裏的合併是淺合併,所以 this.setState({comments}) 完整保留了 this.state.posts, 但是完全替換了 this.state.comments