PureRenderMixin 优化
PureRenderMixin 优化
react最常用的工具就是PureRenderMixin,使用 npm i react-addons-pure-render-mixin --save
,安装并使用:
import React,{Component} from 'react'
import PureRenderMixin from 'react-addons-pure-render-mixin'
class Demo extends Component{
constructor(props, context) {
super(props, context);
this.shouldComponentUpdate = PureRenderMixin.shouldComponentUpdate.bind(this);
}
//省略其他代码....
}
eact的生命周期hook中有个shouldComponentUpdate,组件每一次改动,都要问一下这个函数是否要执行更新,当这个函数返回true,则执行更新。返回false,则不执行更新。默认的情况下,这个函数一直会返回true,即一些无效的更新也会执行。
为什么会有无效的改动?我们都知道,在react组件中,state和props的改变都会触发组件的更新和重新渲染。但是在react中有些时候state和props没有改变也会触发更新。这样就会导致无效的渲染。
这里使用this.shouldComponentUpdate=PureRenderMixin.shouldComponentUpdate.bind(this),实际上是对组件原来的shouldComponentUpdate的方法进行重写,每次更新之前都要查看props和state的是否发生改变,如果改变;就返回false,没有就返回true。
所以我们在react开发中都尽量在组件中加入PureRenderMixin方法去优化性能。