• Component 和 PureComponent 的区别;复制demo,肉眼可以的区别


    React.PureComponent它用当前与之前 props 和 state 的浅比较覆写了 shouldComponentUpdate() 的实现。
    简单来说,就是PureComponent简单实现了shouldComponentUpdate()的功能
    当然,如果你的数据结构比较复杂就不行了

    首先看看第一段代码

     1 import React from 'react'
     2 
     3 class Child extends React.Component {
     4 
     5   render() {
     6     console.log('child render')
     7     return <div>child</div>;
     8   }
     9 }
    10 
    11 class App extends React.Component {
    12   state = {
    13     a: 1,
    14   };
    15 
    16   render() {
    17     console.log('render');
    18     return (
    19       <>
    20         <button
    21           onClick={() => {
    22             this.setState({ a: 2 });
    23           }}
    24         >
    25           Click me
    26         </button>
    27         <Child color={'red'}/>
    28       </>
    29     );
    30   }
    31 }
    32 
    33 export default App

    当我们点击按钮更新了父组件的状态,那么子组件也会重新render,那么这个时候输出的是:

    parent render
    child render

    当我们想优化组件render的时候,我们会使用shouldComponentUpdate() 。那么我现在把上面的 Child 组件替换为如下:

     1 class Child extends React.Component {
     2 
     3   shouldComponentUpdate(nextProps, nextState) {
     4     if (this.props.color !== nextProps.color) {
     5       return true
     6     }
     7   }
     8 
     9   render() {
    10     console.log('child render')
    11     return <div>child</div>;
    12   }
    13 }

    这个时候,我们点击按钮更新父组件状态的时候,子组件的是不会render的,输入的是:

    parent render

    最后,我们在把child组件替换为如下:

    1 class Child extends React.PureComponent {
    2   render() {
    3     console.log('child render')
    4     return <div>child</div>;
    5   }
    6 }

    你会发现它和上图的Child组件是一样的效果,同样只输出了:

    parent render

  • 相关阅读:
    C语言成长学习题(八)
    C语言成长学习题(七)
    C语言成长学习题(六)
    C语言成长学习题(五)
    Linux下zookeeper下载与安装教程
    Linux下mongoDB下载与安装
    并发容器之阻塞队列DelayQueue的使用案例及源码分析
    原子操作CAS-最小的线程安全
    ThreadLocal定义、使用案例及源码分析
    mac上使用git命令上传项目工程源码至Github/gitee
  • 原文地址:https://www.cnblogs.com/ly0612/p/11954414.html
Copyright © 2020-2023  润新知