React第五天 - PureComponent

34 阅读1分钟

组件重复渲染

  • 此时父组件中的 state或者props发生更新的时候,都会执行render; 无论子组件中的 state和props是否更新,都会触发子组件的重新渲染,从而会导致很多不必要的 render开销

  • 解决组件重复渲染

方法一

<b>利用生命周期钩子函数 ShouldComponentUpdate</b>

// 根据最新的 props和state 去判断是否需要调用 redner 方法
// 此方法不推荐,手动的给每个子组件去阻止渲染,真是开发中不是最优选择
/**
 * 
 * @param {*} nextProps 最新的props
 * @param {*} nextState 最新的state
 */ 
shouldComponentUpdate(nextProps, nextState) {
  if (this.props.num !== nextProps.num) {
    return true
  }
  return false
}

方法二

<b>把子组件定义为 PureComponent </b>

import React, { PureComponent } from 'react'

class Header extends PureComponent {
  render() {
    console.log('render Header:')
    return (
      <div>
        Header
      </div>
    )
  }
}

PureComponent 组件优化

  • 简单来说,PureComponent 实现了 shouldComponentUpdate
  • 在 React 中,PureComponent 通过 props和state 的浅比较,浅比较是 react 源码中的一个内置函数
  • 它替代了 shouldComponentUpdate 的工作,它只比较外层数据结构,只要外层相同,则认为没有变化,不会深层次去比较数据(也是个小缺点)

** PureComponent原理 **

当组件更新的时候,如果组件的 props和State 都没有发生改变的时候,render方法就不会出发,省去了 virtualDOM 的生成和对比的过程,所以它能达到提升性能的目的

最好使用在纯展示的组件上
1. 不可以在函数式组件上使用
2. 只是浅比较,深层次的数据不一致,有可能会导致页面得不到更新
3. 不太适合使用在含有多层嵌套对象的 state 和 props 中