zoukankan      html  css  js  c++  java
  • React.memo

    介绍React.memo之前,先了解一下React.ComponentReact.PureComponent

    React.Component

    React.Component是基于ES6 class的React组件。

    React允许定义一个class或者function作为组件,那么定义一个组件类,就需要继承React.Component.

    例如:

    
    class Welcome extends React.Component {
      render() {
        return <h1>Hello, {this.props.name}</h1>;
      }
    }
    

    注意:继承React.Component的React组件类中,render()为必须方法,其他都为可选。

    React.PureComponent

    React.PureComponentReact.Component类似,都是定义一个组件类。不同是React.Component没有实现shouldComponentUpdate(),而 React.PureComponent通过propsstate的浅比较实现了。

    如果组件的propsstate相同时,render的内容也一致,那么就可以使用React.PureComponent了,这样可以提高组件的性能。

    例如:

    
    class Welcome extends React.PureComponent {
      render() {
        return <h1>Hello, {this.props.name}</h1>;
      }
    }
    
    当props和state中有复杂数据结果时,不好使用PureComponent

    React.memo

    React.memo是一个高阶组件,类似于React.PureComponent,不同于React.memofunction组件,React.PureComponentclass组件。

    示例:

    
    const MyComponent = React.memo(props => {
      /* render using props */
      return (
    
      );
    });
    

    这种方式依然是一种对象的浅比较,有复杂对象时无法render。在React.memo中可以自定义其比较方法的实现。

    例如:

    
    function MyComponent(props) {
      /* render using props */
    }
    function areEqual(prevProps, nextProps) {
      /*
      return true if passing nextProps to render would return
      the same result as passing prevProps to render,
      otherwise return false
      */
    }
    export default React.memo(MyComponent, areEqual);
    
    该方法在V16.6.0才支持

    推荐阅读《React 手稿》

    来源:https://segmentfault.com/a/1190000016933809

  • 相关阅读:
    莫比乌斯反演学习笔记
    NOIp 2020 游记
    题解【LOJ3087】「GXOI / GZOI2019」旅行者
    题解【CF999E】Reachability from the Capital
    题解【LOJ2007】「SCOI2015」国旗计划
    题解【LOJ3145】「APIO2019」桥梁
    题解【LOJ2114】「HNOI2015」菜肴制作
    CSP-J/S 2020 爆炸记
    题解【洛谷P2569】[SCOI2010]股票交易
    补题目录
  • 原文地址:https://www.cnblogs.com/datiangou/p/10158690.html
Copyright © 2011-2022 走看看