继承自PureComponent的时候,
再点击的时,不会再输出render,
即不会再重新渲染了
============
用扩展运算符产生新数组,
使this.state.arr的引用发生了变化,
每次点击按钮都会输出render,
界面也会变化,
不管该组件是继承自Component还是PureComponent的
==============
如果state和prop一直变化的话,
还是建议使用Component,
并且PureComponent的最好作为展示组
==================
若是数组和对象等引用类型,
则要引用不同,
才会渲染
================
如果prop和state每次都会变,
那么PureComponent的效率还不如Component,
进行浅比较也是需要时间
==============
若有shouldComponentUpdate,
则执行它,
若没有这个方法会判断是不是PureComponent,
若是,进行浅比较
==================
继承自Component的组件
若是shouldComponentUpdate返回false,
就不会渲染了,
继承自PureComponent的组件
不用我们手动去判断prop和state,
所以在PureComponent中
使用shouldComponentUpdate会有如下警告:
就是不要在PureComponent中使用shouldComponentUpdate,
===============
options.push(new Option())
options.splice(0, 1)
options[i].name = "Hello"
在原对象上进行修改,
由于浅比较是比较指针的异同,
所以会认为不需要进行重绘。
===================
immutable.js
会在每次对原对象进行添加,删除,
修改使返回新的对象实例。
任何对数据的修改都会导致数据指针的变化。
==================
=====================
陷阱
Literal Array与Literal Object
{this.props.items.map(i =>
<Cell data={i} options={this.props.options || []} />
)}
若options为空,
则会使用[]。
[]每次会生成新的Array,
因此导致Cell每次的props都不一样,
导致需要重绘。
解决方法如下:
const default = [];
{this.props.items.map(i =>
<Cell data={i} options={this.props.options || default} />
)}
=====================
内联函数
函数也经常作为props传递,
由于每次需要为内联函数创建一个新的实例,
所以每次function都会指向不同的内存地址。
比如:
render() {
<MyInput onChange={e => this.props.update(e.target.value)} />;
}
以及:
update(e) {
this.props.update(e.target.value);
}
render() {
return <MyInput onChange={this.update.bind(this)} />;
}
===============
注意第二个例子也会导致创建新的函数实例。
为了解决这个问题,需要提前绑定this指针:
constructor(props) {
super(props);
this.update = this.update.bind(this);
}
update(e) {
this.props.update(e.target.value);
}
render() {
return <MyInput onChange={this.update} />;
}
网友评论