React 最基本的优化方式是使用PureRenderMixin,安装工具 npm i react-addons-pure-render-mixin --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); this.state = { // } } //...省略其他内容... }
React 有一个生命周期 hook 叫做shouldComponentUpdate
,组件每次更新之前,都要过一遍这个函数,如果这个函数返回true
则更新,如果返回false
则不更新。而默认情况下,这个函数会一直返回true
,就是说,如果有一些无效的改动触发了这个函数,也会导致无效的更新
那么什么是无效的改动?之前说过,组件中的props
和state
一旦变化会导致组件重新更新并渲染,但是如果props
和state
没有变化也莫名其妙的触发更新了呢(这种情况确实存在)———— 这不就导致了无效渲染吗?
这里使用this.shouldComponentUpdate = PureRenderMixin.shouldComponentUpdate.bind(this);
的意思是重写组件的shouldComponentUpdate
函数,在每次更新之前判断props
和state
,如果有变化则返回true
,无变化则返回false
。
因此,我们在开发过程中,在每个 React 组件中都尽量使用PureRenderMixin