解读 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 手稿》

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 3. JSX JSX是对JavaScript语言的一个扩展语法, 用于生产React“元素”,建议在描述UI的时候...
    pixels阅读 2,919评论 0 24
  • 作为一个合格的开发者,不要只满足于编写了可以运行的代码。而要了解代码背后的工作原理;不要只满足于自己的程序...
    六个周阅读 8,546评论 1 33
  • It's a common pattern in React to wrap a component in an ...
    jplyue阅读 3,318评论 0 2
  • 40、React 什么是React?React 是一个用于构建用户界面的框架(采用的是MVC模式):集中处理VIE...
    萌妹撒阅读 1,075评论 0 1
  • 今天的React题没有太多的故事…… 半个月前出了248个Vue的知识点,受到很多朋友的关注,都强烈要求再出多些R...
    浪子神剑阅读 10,142评论 6 106