为了账号安全,请及时绑定邮箱和手机立即绑定

React State Updates are Merged?怎么理解?

React State Updates are Merged?怎么理解?

元芳怎么了 2018-10-03 13:18:42
State Updates are MergedWhen 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()一次?这么理解有问题么?
查看完整描述

1 回答

?
慕姐8265434

TA贡献1813条经验 获得超2个赞

这个的意思是指,
setState方法在执行时,会作多个要更动state的合并,以及有类似异步的处理,
这是React中隐性的运行机制,目的主要是为了优化与性能。

分离的那个代码示例,是因为起了两个不同的异步,所以会让两个setState方法分开运行。

关于setState方法,可以参考我写的这篇文章: 为何说setState方法是异步的?


查看完整回答
反对 回复 2018-11-15
  • 1 回答
  • 0 关注
  • 633 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号