react 性能优化

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,就是说,如果有一些无效的改动触发了这个函数,也会导致无效的更新

那么什么是无效的改动?之前说过,组件中的propsstate一旦变化会导致组件重新更新并渲染,但是如果propsstate没有变化也莫名其妙的触发更新了呢(这种情况确实存在)———— 这不就导致了无效渲染吗?

这里使用this.shouldComponentUpdate = PureRenderMixin.shouldComponentUpdate.bind(this);的意思是重写组件的shouldComponentUpdate函数,在每次更新之前判断propsstate,如果有变化则返回true,无变化则返回false

因此,我们在开发过程中,在每个 React 组件中都尽量使用PureRenderMixin

猜你喜欢

转载自www.cnblogs.com/xzqking/p/9111034.html