为什么使用setState
setState来自于Component原型
vue中数据更新
模板渲染
- template转化为render函数
- render函数,经过h函数,即createElement('div', config, children)
数据更新:
- 通过数据劫持,为每个data属性增加setter,当data数据发生变化,dep.notify()=>wacher.update()
react中数据更新
界面渲染
- jsx中通过render函数return渲染内容,渲染内容核心调用了React.createElemente('div', config, children)
数据更新
- 必须依赖几个事件,才能发生渲染。目前主要用到的是this.setState()只要调用了setState,就会触发render
react为什么用setState?
因为没有内部的数据劫持和监听,所以需要依赖一些固定API方法,告诉react,进行重新渲染
提问:setState({message: ''})调用了,变量值没变,会调用render吗?
回答:会!
性能评估:这样显然是比较性能的,解决方案有两种:第一通过shouldComponentUpdate(){return true}
通过preState和state值的对比,来确定是否需要调用render;第二种,使用pureComponent.