zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    《 动态规划_ 货币系统 》
    《动态规划_入门 LIS 问题 》
    数据库中左连接、右连接、全连接的区别
    http和https的区别与联系
    【复习周之流水账记录】
    web前端整套面试题(三)--网易的面试题
    微信小程序相关三、css写小黄人
    CSS选择器的匹配规则
    web前端整套面试题(二)--今日头条面试题
    有趣的逻辑题
  • 原文地址:https://www.cnblogs.com/ly0612/p/11954414.html
Copyright © 2011-2022 走看看