使用PureComponent 和 memo进行React性能优化

前言

关于React性能优化,有各种方法。今天,我们主要使用两个官方推出的组件模式来进行切入,优化点主要基于防止组件进行不必要的render渲染以提升性能。


react原生渲染机制的性能问题

首先来看个简单的栗子,有父子两个组件:

// 父组件
import React, { Component } from 'react';
import './App.css';
import SonComponent from './SonComponent';

class FatherComponent extends Component {
  constructor() {
    super();
    this.state = {
      fatherMsg: "who's your daddy",
      sonMsg: "I'm son"
    }
  }

  render() {
    const { fatherMsg, sonMsg } = this.state;
    console.log('fatherMsg', fatherMsg);
    return (
      <div>
        <button
          onClick={() => {this.setState({fatherMsg: 'father || ' + Date.now()})}}>
          变换fatherMsg值</button>
        <SonComponent sonMsg={sonMsg}></SonComponent>
      </div>
    );

  }
}

export default FatherComponent;

父亲组件作为容器组件,管理两个状态,一个fatherMsg用于管理自身组件,一个sonMsg用于管理子组件状态。按钮点击事件用于修改父组件状态。

// 子组件
import React, { Component } from 'react';

class SonComponent extends Component {
  
  render() {
    const { sonMsg } = this.props;
    console.log('sonMsg', sonMsg + ' || ' + Date.now());
    return (
    <div>{sonMsg}</div>
    )
  }
}

export default SonComponent;

当页面初始化时,打印出了两条数据:

初始化打印值

这很正常,页面初始化时,react进行dom树的建设与渲染,数据自上而下流动,由父到子打印出了两个值。
当我们点击按钮改变父组件状态时,奇怪的事情发生了:
子组件并没有用到父组件的fatherMsg,但是当fatherMsg变化时,虽然子组件的props并没有变化,但子组件也跟着父组件更新并重新render了:
子组件跟着父组件重新渲染

对,这就是react原生渲染机制的问题:当父组件更新时,子组件无论props是否改变,都进行了重新渲染,造成了性能浪费
我们知道,对一个组件的dom进行render,特别是当dom树较为复杂时,是相当消耗时间和性能的,应尽量避免。以上截图中的2ms,就是这次浪费的时间,而这只是一个最简单的组件,复杂的组件会消耗更多。
我们想要的,是当子组件props更新之后,才对子组件进行重新render。

使用shouldComponentUpdate进行人为干预

我们先来温习一下react生命周期:

react生命周期

可以看到,在updating阶段,有一个钩子shouldComponentUpdate,它会返回一个boolean值,以控制组件是否更新。同时会接收两个参数:新的props和新的state。我们来试试:

import React, { Component } from 'react';

class SonComponent extends Component {
  shouldComponentUpdate(nextProps, nextState){
    console.log('当前现有的props值为'+ this.props.sonMsg);
    console.log('即将传入的props值为'+ nextProps.sonMsg);
  }
  
  render() {
    const { sonMsg } = this.props;
    console.log('sonMsg', sonMsg + ' || ' + Date.now());
    return (
    <div>{sonMsg}</div>
    )
  }
}

export default SonComponent;

打印值

可以看到,当点击按钮触发子组件更新时,触发了shouldComponentUpdate,但我故意没有return。所以控制台报错。这时子组件并没有更新。
修改返回值:

shouldComponentUpdate(nextProps,nextState){
        console.log('当前现有的props值为'+ this.props.sonMsg);
        console.log('即将传入的props值为'+ nextProps.sonMsg);
        return this.props.sonMsg !== nextProps.sonMsg
 }   

这时,就实现了我们想要的:只有当props变化时,才更新子组件。
但是,在实际开发中,我们的子组件往往不止有一个props。当有多个属性时,就需要一个个对比,会使代码非常难看。
并且,如果是对象这种引用类型,是无法通过简单的===进行比较的。
这时,可以采取一种取巧的方法,即序列化props后进行比较:

shouldComponentUpdate(nextProps,nextState){
        return JSON.stringify(this.props) !== JSON.stringify(nextProps)
 }   

但是,当props上挂载function时,会产生问题:

JSON.stringify(function() {})  // undefined

并且,由于对象是无序的,当对象成员顺序发生变化时,序列化方法不再生效。
这种方法,在大部分情况下是适用的。只要注意以上说明的几种特殊情况就好。

使用PureComponent

如果每个组件都需要使用shouldComponentUpdate来控制更新,那也太low了。
react官方提供了PureComponent模式解决默认情况下子组件渲染策略的问题。

// 子组件
import React, { PureComponent } from 'react';

class SonComponent extends PureComponent {
  
  render() {
    const { sonMsg } = this.props;
    console.log('sonMsg', sonMsg + ' || ' + Date.now());
    return (
    <div>{sonMsg}</div>
    )
  }
}

export default SonComponent;

当父组件修改跟子组件无关的状态时,再也不会触发自组件的更新了。
用PureComponent会不会有什么缺点呢?
刚才我们是传入一个string字符串(基本数据类型)作为props传递给子组件。
现在我们是传入一个object对象(引用类型)作为props传递给子组件。看看效果如何:

// 父组件
import React, { Component } from 'react';
import './App.css';
import SonComponent from './SonComponent';

class FatherComponent extends Component {
  constructor() {
    super();
    this.state = {
      fatherMsg: "who's your daddy",
      sonMsg: {
        val: "I'm son"
      }
    }
  }

  render() {
    const { fatherMsg, sonMsg } = this.state;
    console.log('fatherMsg', fatherMsg);
    return (
      <div>
        <button
          onClick={() => {
            sonMsg.val = 'son' + Date.now();
            this.setState({ sonMsg })}
          }>
          变换sonMsg值</button>
        <SonComponent sonMsg={sonMsg}></SonComponent>
      </div>
    );

  }
}

export default FatherComponent;

当我们点击按钮修改了sonMsg时,发现子组件并没有更新,为什么?
因为PureComponent 对状态的对比是浅比较
遇到了和shouldComponentUpdate同样的问题。关于深浅比较和拷贝,可以参考我的这篇文章
解决这个问题,我们可以采用更换新指针或者深拷贝来解决:

         this.setState(({sonMsg}) =>
          { 
            return {
              sonMsg:{
                ...sonMsg,
                val:'son' + Date.now()
              }
            }
          })

React.PureComponent 中的 shouldComponentUpdate() 仅作对象的浅层比较。如果对象中包含复杂的数据结构,则有可能因为无法检查深层的差别,产生错误的比对结果。仅在你的 props 和 state 较为简单时,才使用 React.PureComponent,或者在深层数据结构发生变化时调用 forceUpdate() 来确保组件被正确地更新。你也可以考虑使用 immutable 对象加速嵌套数据的比较。

此外,React.PureComponent 中的 shouldComponentUpdate() 将跳过所有子组件树的 prop 更新。因此,请确保所有子组件也都是“纯”的组件。

使用forceUpdate

在react生命周期图中,我们看到一个叫forceUpdate的钩子。它的作用是强制更新组件。当我们没有把握对于复杂props对比更新时,可以采用这个方法,对props进行手动检测后进行强制更新。

使用React.memo

上述我们花了很大篇幅,讲的都是class组件,但是随着hooks出来后,更多的组件都会偏向于function 写法了。React 16.6.0推出的重要功能之一,就是React.memo。

React.memo 为高阶组件。它与 React.PureComponent 非常相似,但它适用于函数组件,但不适用于 class 组件。

如果你的函数组件在给定相同 props 的情况下渲染相同的结果,那么你可以通过将其包装在 React.memo 中调用,以此通过记忆组件渲染结果的方式来提高组件的性能表现。这意味着在这种情况下,React 将跳过渲染组件的操作并直接复用最近一次渲染的结果。

默认情况下其只会对复杂对象做浅层对比,如果你想要控制对比过程,那么请将自定义的比较函数通过第二个参数传入来实现。

function MyComponent(props) {
  /* 使用 props 渲染 */
}
function areEqual(prevProps, nextProps) {
  /*
  如果把 nextProps 传入 render 方法的返回结果与
  将 prevProps 传入 render 方法的返回结果一致则返回 true,
  否则返回 false
  */
}
export default React.memo(MyComponent, areEqual);

此方法仅作为性能优化的方式而存在。但请不要依赖它来“阻止”渲染,因为这会产生 bug。

此方法在函数式组件中非常有用,因为在函数式组件中没有shouldComponentUpdate方法。

结语

本文所进行的react性能优化,都是针对避免子组件进行不必要的更新来开展的。以上几种方法都可以实现这种优化,分别适合不同的场景。
但对于比较复杂类型这种棘手的问题,所有方法都必须进行一定的处理,要么在父组件进行指针层面的更新,要么在子组件进行深度比较来控制是否更新。
不管怎样,在对前端代码进行性能优化这项浩大的工程上,我们都前进了一小步。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容