ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

React性能优化之shouldComponentUpdate、PureComponent和React.memo

2021-07-04 14:30:29  阅读:141  来源: 互联网

标签:shouldComponentUpdate Child React state props 组件 PureComponent


React性能优化之shouldComponentUpdate、PureComponent和React.memo

前言

最近一直在学习关于React方面的知识,并有幸正好得到一个机会将其用在了实际的项目中。所以我打算以博客的形式,将我在学习和开发(React)过程中遇到的问题记录下来。

这两天遇到了关于组件不必要的重复渲染问题,看了很多遍官方文档以及网上各位大大们的介绍,下面我会通过一些demo结合自己的理解进行汇总,并以此作为学习React的第一篇笔记(自己学习,什么都好,就是费头发…)。

本文主要介绍以下三种优化方式(三种方式有着相似的实现原理):

  • shouldComponentUpdate
  • React.PureComponent
  • React.memo

其中shouldComponentUpdateReact.PureComponent是类组件中的优化方式,而React.memo是函数组件中的优化方式。

引出问题

  1. 新建Parent类组件。
import React, { Component } from 'react'
import Child from './Child'

class Parent extends Component {
  constructor(props) {
    super(props)
    this.state = {
      parentInfo: 'parent',
      sonInfo: 'son'
    }
    this.changeParentInfo = this.changeParentInfo.bind(this)
  }

  changeParentInfo() {
    this.setState({
      parentInfo: `改变了父组件state:${Date.now()}`
    })
  }

  render() {
    console.log('Parent Component render')
    return (
      <div>
        <p>{this.state.parentInfo}</p>
        <button onClick={this.changeParentInfo}>改变父组件state</button>
        <br/>
        <Child son={this.state.sonInfo}></Child>
      </div>
    )
  }
}

export default Parent


  1. 新建Child类组件。
import React, {Component} from 'react'

class Child extends Component {
  constructor(props) {
    super(props)
    this.state = {}
  }

  render() {
    console.log('Child Component render')
    return (
      <div>
        这里是child子组件:
        <p>{this.props.son}</p>
      </div>
    )
  }
}

export default Child


  1. 打开控制台,我们可以看到控制台中先后输出了Parent Component renderChild Component render

img 点击按钮,我们会发现又输出了一遍Parent Component renderChild Component renderimg 点击按钮时我们只改变了父组件Parentstate中的parentInfo的值,Parent更新的同时子组件Child也进行了重新渲染,这肯定是我们不愿意看到的。所以下面我们就围绕这个问题介绍本文的主要内容。

shouldComponentUpdate

React提供了生命周期函数shouldComponentUpdate(),根据它的返回值(true | false),判断 React 组件的输出是否受当前 state 或 props 更改的影响。默认行为是 state 每次发生变化组件都会重新渲染(这也就说明了上面

标签:shouldComponentUpdate,Child,React,state,props,组件,PureComponent
来源: https://blog.csdn.net/qq_27575925/article/details/118461926

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有