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

  • 相关阅读:
    sublime开启vim模式
    git命令行界面
    搬进Github
    【POJ 2886】Who Gets the Most Candies?
    【UVA 1451】Average
    【CodeForces 625A】Guest From the Past
    【ZOJ 3480】Duck Typing
    【POJ 3320】Jessica's Reading Problemc(尺取法)
    【HDU 1445】Ride to School
    【HDU 5578】Friendship of Frog
  • 原文地址:https://www.cnblogs.com/ly0612/p/11954414.html
Copyright © 2011-2022 走看看