When you call setState(), React merges the object you provide into the current state.
For example, your state may contain several independent variables:
constructor(props) {
super(props);
this.state = {
posts: [],
comments: []
};
}
Then you can update them independently with separate setState() calls:
componentDidMount() {
fetchPosts().then(response => {
this.setState({
posts: response.posts
});
});
fetchComments().then(response => {
this.setState({
comments: response.comments
});
});
}
The merging is shallow, so this.setState({comments}) leaves this.state.posts intact, but completely replaces this.state.comments.
这个意思是多个state分开更新,会在合并之后然后执行render() 而不是更新一个state render()一次?
这么理解有问题么?
React 更新好 state 数据之后,会先去刷新虚拟 DOM ,然后再是虚拟 DOM 与真实 DOM 的同步吧(此处不是根据虚拟 DOM 完整刷一遍真实 DOM)。