首页 > 其他分享 >面试官:React怎么做性能优化

面试官:React怎么做性能优化

时间:2022-11-15 08:34:05浏览次数:33  
标签:面试官 Parent Child React state props 组件 优化

前言

最近一直在学习关于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 点击按钮,我们会发现又输出了一遍Parent Component renderChild Component render 点击按钮时我们只改变了父组件Parentstate中的parentInfo的值,Parent更新的同时子组件Child也进行了重新渲染,这肯定是我们不愿意看到的。所以下面我们就围绕这个问题介绍本文的主要内容。

shouldComponentUpdate

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

标签:面试官,Parent,Child,React,state,props,组件,优化
From: https://www.cnblogs.com/beifeng1996/p/16891199.html

相关文章