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

另外的方法

1 取掉 .map 

  map文件是帮助我们查看报错的位置的。

  map文件由devtool属性控制,如果不想要map,注释掉就可以,大约webpack.config.prod.js第57行;

2 分包

  分包 用 react-loadable  

  https://yq.aliyun.com/articles/607992

  https://www.jianshu.com/p/697669781276

3 提取第三方库

  目前推荐用 DLL 的方式提取第三方库。

4 gzip压缩

  gzip压缩 也需要 服务端来配合

更多优化可移步

【第1281期】React 16 加载性能优化指南

彻底解决 webpack 打包文件体积过大

原文地址:https://www.cnblogs.com/xzqyun/p/9111034.html