React性能优化之PureComponent 和 memo使用分析

5,094 阅读7分钟

前言

关于react性能优化,在react 16这个版本,官方推出fiber,在框架层面优化了react性能上面的问题。由于这个太过于庞大,我们今天围绕子自组件更新策略,从两个及其微小的方面来谈react性能优化。 其主要目的就是防止不必要的子组件渲染更新

子组件何时更新?shouldComponentUpdate?

首先我们看个例子,父组件如下:

import React,{Component} from 'react';
import ComponentSon from './components/ComponentSon';
import './App.css';

class App extends Component{

  state = {
    parentMsg:'parent',
    sonMsg:'son'
  }
  render(){
    return (
      <div className="App">
        <header className="App-header" onClick={()=> {this.setState({parentMsg:'parent' + Date.now()})}}>
          <p>
           {this.state.parentMsg}
          </p>
        </header>
        <ComponentSon sonMsg={this.state.sonMsg}/>
      </div>
    );}
}

export default App;

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

子组件写法如下:

import React,{Component} from 'react';
export default class ComponentSon extends Component{
   render(){
       console.log('Component rendered : ' + Date.now());
       const msg = this.props.sonMsg;
       return (
           <div> {msg}</div>
       )
   }
}

无论什么点击哪个事件,都会触发 ComponentSon 的渲染更新。 控制台也可以看到自组件打印出来的信息:

PureComponent rendered : 1561790880451

但是这并不是我们想要的吧?按理来说,子组件需要用到的那个props更新了,才会重新渲染更新,这个才是我们想要的。还好React 的class组件类中的shouldComponentUpdate可以解决我们的问题。

// shouldComponentUpdate 
import React,{Component} from 'react';
export default class ComponentSon extends Component{
 shouldComponentUpdate(nextProps,nextState){
     console.log('当前现有的props值为'+ this.props.sonMsg);
     console.log('即将传入的props值为'+ nextProps.sonMsg);
 }
 render(){
     console.log('PureComponent rendered : ' + Date.now());
     const msg = this.props.sonMsg;
     return (
         <div> {msg}</div>
     )
 }
}

注意,这个shouldComponentUpdate要返回一个boolean值的,这里我没有返回,看看控制台怎么显示?当我点击修改parentMsg的元素时:

当前现有的props值为son
即将传入的props值为son

Warning: ComponentSon.shouldComponentUpdate(): Returned undefined instead of a boolean value. Make sure to return true or false.

也就是说,控制台给出了一个警告,同时shouldComponentUpdate默认返回true,即要更新子组件。因此,避免props没有发生变化的时候更新,我们可以修改shouldComponentUpdate:

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

这样就解决了不必要的更新。

PureComponent 更新原理(class 组件)

在上述例子中,我们看到了shouldComponentUpdate在 class 组件上的积极作用,是不是每个class组件都得自己实现一个shouldComponentUpdate判断呢?react 官方推出的PureComponent就封装了这个,帮忙解决默认情况下子组件渲染策略的问题。

import React,{PureComponent} from 'react';
export default class ComponentSon extends PureComponent{
    render(){
        console.log('PureComponent rendered : ' + Date.now());
        const msg = this.props.sonMsg;
        return (
            <div> {msg}</div>
        )
    }
}

当父组件修改跟子组件无关的状态时,再也不会触发自组件的更新了。

用PureComponent会不会有什么缺点呢?

刚才我们是传入一个string字符串(基本数据类型)作为props传递给子组件。 现在我们是传入一个object对象(引用类型)作为props传递给子组件。看看效果如何:

import React,{Component} from 'react';
import ComponentSon from './components/ComponentSon';
import './App.css';

class App extends Component{

  state = {
    parentMsg:'parent',
    sonMsg:{
      val:'this is val of son'
    }
  }
  render(){
    return (
      <div className="App">
        <header className="App-header" onClick={()=> {this.setState({parentMsg:'parent' + Date.now()})}}>
          <p>
           {this.state.parentMsg}
          </p>
        </header>
        <button onClick={()=>
          this.setState(({sonMsg}) =>
          { 
            sonMsg.val = 'son' + Date.now();
            console.table(sonMsg);
            return {sonMsg}
          })
          }>修改子组件props</button>
        <ComponentSon sonMsg={this.state.sonMsg}/>
      </div>
    );}
}

export default App;

当我们点击button按钮的时候,触发了setState,修改了state,但是自组件却没有跟新。为什么呢?这是因为:

PureComponent 对状态的对比是浅比较的

PureComponent 对状态的对比是浅比较的

PureComponent 对状态的对比是浅比较的

this.setState(({sonMsg}) =>
          { 
            sonMsg.val = 'son' + Date.now();
            console.table(sonMsg);
            return {sonMsg}
          })

这个修改state的操作就是浅复制操作。什么意思呢?这就好比

let obj1 = {
    val: son
}
obj2 = obj1;

obj2.val = son + '1234'; // obj1 的val 也同时被修改。因为他们指向同一个地方引用

obj1 === obj2;// true

也就是说,我们修改了新状态的state,也修改了老状态的state,两者指向同一个地方。PureComponent 发现你传入的props 和 此前的props 一样的,指向同一个引用。当然不会触发更新了。

那我们应该怎么做呢?react 和 redux中也一直强调,state是不可变的,不能直接修改当前状态,要返回一个新的修改后状态对象

因此,我们改成如下写法,就可以返回一个新的对象,新对象跟其他对象肯定是不想等的,所以浅比较就会发现有变化。自组件就会有渲染更新。

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

除了上述写法外,我们可以使用Object.assign来实现。也可以使用外部的一些js库,比如Immutable.js等。

而此前的props是字符串字符串是不可变的(Immutable)。什么叫不可变呢?就是声明一个字符串并赋值后,字符串再也没法改变了(针对内存存储的地方)。

let str = "abc"; // str 不能改变了。
str +='def' // str = abcdef 

看上去str 由最开始的 ‘abc’ 变为‘abcdef’变了,实际上是没有变。 str = ‘abc’的时候,在内存中开辟一块空间栈存储了abc,并将str指向这块内存区域。 然后执行 str +='def'这段代码的时候,又将结果abcdef存储到新开辟的栈内存中,再将str指向这里。因此原来的内存区域的abc一直没有变化。如果是非全局变量,或没被引用,就会被系统垃圾回收。

forceUpdate

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

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

memo

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

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

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

// 子组件
export default function Son(props){
    console.log('MemoSon rendered : ' + Date.now());
    return (
        <div>{props.val}</div>
    )
}

上述跟class组件中没有继承PureComponent一样,只要是父组件状态更新的时候,子组件都会重新渲染。所以我们用memo来优化:

import React,{memo} from 'react';

 const MemoSon =  memo(function Son(props){
    console.log('MemoSon rendered : ' + Date.now());
    return (
        <div>{props.val}</div>
    )
})
export default MemoSon;

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

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

注意点如下:

  • 此方法仅作为性能优化的方式而存在。但请不要依赖它来“阻止”渲染,因为这会产生 bug。
  • 与 class 组件中 shouldComponentUpdate() 方法不同的是,如果 props 相等,areEqual 会返回 true;如果 props 不相等,则返回 false。这与 shouldComponentUpdate 方法的返回值相反。

结语

本次我们讨论了react组件渲染的优化方法之一。class组件对应PureComponent,function组件对应memo。也简单讲述了在使用过程中的注意点。后续开发组件的时候,或许能对性能方面有一定的提升。