PureRenderMixin优化
React最基础的优化方式是使用PrueRenderMixin
安装
npm install react-addons-pure-render-minin --save 然后在组件中引用
import React from ‘react’;
import PureRenderMixin from ‘react-addons-pure-render-mixin’;
class list extends React.Component{
constructor(props,context){
super(props,context);
this.shouldComponentUpdate=PureRenderMixin.shouldComponentUpdate.bind(this);
}
}
React 有一个生命周期shouldComponentUpdate,组件每次更新之前。都要调用该函数,如果这个函数返回true则更新,如果返回false则不更新,而默认情况下,这个函数会一直返回 true,就是说如果有一些无效的改动触发这个函数,也会导致的更新。
之前说过组件中的props和state一旦变化会导致组件重新更新并渲染,但是如果props和state没有变化也莫名的触发更新 这不就导致了无效渲染吗?
这里使用 this.shouldComponentUpdate=PureRenderMixin.shouldComponentUpdate.bind(this)意思是与组件的shouldComponentUpdate函数,在每次更新之前判断props和state 如果有变化则返回true,无变化则返回false
因此,我们在开发过程中,在每个React组件中都尽量使用PureRenderMixin