避免组件重复渲染性能优化
###避免组件重复渲染性能优化
#####使用shouldComponentUpdate方法,该函数默认返回true,表示只要传给组件的props或本身state有变化,就重新render,因此可以通过使用方式如下:
shouldComponentUpdate(nextProps, nextState) {
return nextProps.data !== this.props.data;
}
注意事项:
1、请只传递component需要的props,避免其他props变化导致重新渲染(慎用延展属性)
2、尽量使传给子组件的数据扁平化,若存在深层嵌套的比较,建议在shouldComponentUpdate中使用Immutable的is函数进行比较,否则会造成比较结果不准确
3、别忘了shouldComponentUpdate也需要比较state
4、请慎用setState,容易导致重新渲染 ***
####另外处理重复render的库有react-addons-pure-render-mixin及react-immutable-render-mixin等
(1)react-addons-pure-render-mixin:
只能对props和state数据作浅比较,若props和state数据为深层嵌套时,则可能会发生误判,需结合immutable一块使用
(2)react-immutable-render-mixin:
为react-addons-pure-render-mixin和immtable的is函数结合的库,达到的效果相当于shouldComponentUpdate中使用了Immutable的is函数,但若shouldComponentUpdate里只是限制props.data发生变化时才render,则也需要重写shouldComponentUpdate,如下所示
shouldComponentUpdate(nextProps, nextState) {
return !shallowEqualImmutable(this.props.data, nextProps.data) ||!shallowEqualImmutable(this.state.data, nextState.data);
}
综上:目前针对p-beisencloud-core为避免重复渲染给出的方案为直接使用shouldComponentUpdate,有针对性的避免渲染
暂时不考虑react-immutable-render-mixin库的原因是:目前项目中从传入数据的方式来看都需要shouldComponentUpdate,即使使用该库也需要,即有它无它都是一样的