避免重复渲染,React 的纯组件。

477 阅读2分钟

为了提升性能,减少渲染次数,React 有了纯组件。只要 state 和 props 一致,就不用再次 render,结果保持一致。

shouldComponentUpdate

在 React 官方文档中,生命周期函数中的 shouldComponentUpdate 有着特殊的意义。它的主要作用是:根据 shouldComponentUpdate() 的返回值,判断 React 组件的输出是否受当前 state 或 props 更改的影响。

就是说 shouldComponentUpdate 函数默认返回 true ,任何 props 的更改,任何的 setState 的操作都会导致界面的重新 render,返过来返回 false ,这些操作就无法导致界面的 render,举例如下:

//App.js
import React from "react"
class App extends React.Component {
  constructor(props){
    super(props)
    this.state = {
      name:"gougou"
    }
    this.onclick = this.onclick.bind(this)
  }
  onclick(){
    this.setState({
      name:"勾勾"
    })
  }
  shouldComponentUpdate(nextProps, nextState){
    return false;
  }
  render(){
    return (
      <div>
        hello world
        <p onClick = {this.onclick}>{this.state.name}</p>
      </div>
    )
  }

shouldComponentUpdate 函数里,我们强制修改了它的返回值为 false,结果我们在点击 p 标签的时候,是无法更改里面的内容的。

在 React 中,这个方法的唯一用途就是性能优化。也就是说当 props 和 state 没有发生改变的时候,我们不需要页面重新 render。为满足这一要求,我们就需要去搞清楚实现 shouldComponentUpdate 的逻辑,对比新旧 props 和 state,但 React 不允许我们这样做。React 自己提出了 PureComponent 纯组件的概念。

PureComponent

PureComponent 是 React 的内置组件,它会替代 shouldComponentUpdate 对 props 和 state 进行浅层比较。

浅层比较就是对引用地址的比较,主要分两类。

  • 基本数据类型,就是单纯的值比较 1 == 1 true == true

  • 引用类型,比如数组、对象就是地址的比较,如下例:

    class App extends React.PureComponent { constructor(props){ super(props) this.state = { name:["gougou"] } this.onclick = this.onclick.bind(this) } onclick(){ this.state.name[0] = '勾勾'; this.setState({ name:this.state.name }) } render(){ return (

    hello world

    {this.state.name}

    ) }

上面这个案例的 name 是一个数组,再修改里面的第一个元素值为“勾勾”,但是这个引用地址还是之前的那个地址,所以当我们点击的时候,组件只是做了浅层对比,name 的引用地址是一样的。虽然内容不一样,但不会导致界面发生 render。

当我们了解了 Component 和 PureComponent 的基本情况后,就能尽量避免一些不必要的重复渲染。