反应中的备忘录是什么?

Hem*_*ari 2 javascript reactjs react-native

我正在学习最新的反应功能。根据码头备忘录的工作方式shouldComponentUpdatePureComponent在功能组件中,但我如何在功能组件中使用此备忘录概念。

假设我有以下组件使用类

import React, { Component } from 'react';
class Test extends Component {
   shouldComponentUpdate(nextProps, nextState) {
     return this.props.text != nextProps.text;
   }
   render(){
     const { text } = this.props;
     return(
       <div>
          <h1>{text}</h1>
       </div>
     )
   }
}
Run Code Online (Sandbox Code Playgroud)

功能组件

function Test = props => {
  const { text } = props;
     return(
       <div>
          <h1>{text}</h1>
       </div>
     )
}
Run Code Online (Sandbox Code Playgroud)

如何在功能组件中使用备忘录编写类组件

Kei*_*ter 5

Memo 作为一个高阶组件工作,你可以简单地用它包装你的功能组件导出。每次应用程序更新时,memo 都会自动对 props 进行浅层比较,以确定它们是否已更改,以及组件是否需要重新渲染。

export default React.memo(Test);
Run Code Online (Sandbox Code Playgroud)


小智 5

React.memo()是一个HOC,它接受一个函数组件并返回一个行为与 PureComponent 相同的组件。

const MyComponent = React.memo(function MyComponent(props) {
  /* only rerenders if props change */
});
Run Code Online (Sandbox Code Playgroud)

更新:React.memo 还接受比较函数作为第二个参数。通过使用这个函数,我们可以不以浅薄的方式比较 props,而是以任何我们想要的方式。这可以更好地控制防止组件更新。当您的 props 包含复杂的对象并且您想要比较这些对象的字段同时确定组件是否应该更新时,请使用此函数。例如

const MyComponent = React.memo(function MyComponent(props) {
/* only rerenders if props change */
}, (props1, props2) => {
prop1.my_property_to_check === prop2.my_property_to_check
});
Run Code Online (Sandbox Code Playgroud)