javascript - React State Updates are Merged?怎么理解?
PHPz
PHPz 2017-04-11 11:46:41
[JavaScript讨论组]

State Updates are Merged

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()一次?
这么理解有问题么?

PHPz
PHPz

学习是最好的投资!

全部回复(2)
PHP中文网

React 更新好 state 数据之后,会先去刷新虚拟 DOM ,然后再是虚拟 DOM 与真实 DOM 的同步吧(此处不是根据虚拟 DOM 完整刷一遍真实 DOM)。

高洛峰

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

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

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

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号