掌握React.Memo

React.memo gives us the ability of pure components in React but for functional based components rather than class based ones.

React.memo使我们能够在React中使用纯组件,但可以使用基于功能的组件,而不是基于类的组件。

memoization is computer science jargon which means caching the result of expensive function calls and returning the cached version when the arguments are the same.

memoization是计算机科学的行话,这意味着缓存昂贵的函数调用的结果,并在参数相同时返回缓存的版本。

In React terms:

用React术语:

We don’t want MyNewComponent re-rendering when the props being passed are the same.

当传递的props相同时,我们不希望MyNewComponent重新渲染。

简单的计数器示例 (Simple Counter Example)

I’ve created the following example in Codesandbox to help cement in your mind how React.memo works.

Codesandbox创建了以下示例,以帮助您牢记React.memo工作方式

It’s a simple app that counts the number of times a button is clicked. You can see from the below screenshot we have a banner on top of the page.

这是一个简单的应用程序,可以计算按钮被点击的次数。 您可以从下面的屏幕截图中看到,页面顶部有一个横幅。

Imagine the Banner is a UI component that can have different types, in this case you want to use the info type banner so you create your Banner as follows:

想象一下, Banner是一个可以具有不同类型的UI组件,在这种情况下,您要使用info类型横幅广告,因此您可以如下创建Banner

<Banner type="info" />

Our CounterComponent looks like this:

我们的CounterComponent看起来像这样:

class CounterComponent extends Component {
  state = { buttonPressedCount: 0 };
  render() {
    const { buttonPressedCount } = this.state;
    return (
      <div className="new-component">
        <h4>Button Pressed Count: {buttonPressedCount}</h4>
        <button
          onClick={() =>
            this.setState({ buttonPressedCount: buttonPressedCount + 1 })
          }
        >
          Increase Count
        </button>
        <Banner type="info" />
      </div>
    );
  }
}

And our Banner component looks as follows:

我们的Banner组件如下所示:

const Banner = props => {
  const { type } = props;

  if (type === "info") {
    return <div className="info-banner">I am an info banner</div>;
  }
};

In our CounterComponent, every time we click the button we increase the buttonPressedCount variable which causes a re-render which is what you would expect. The problem with this is that the Banner component also re-renders even though the props being passed to it haven’t changed.

CounterComponent ,每次单击按钮时,都会增加buttonPressedCount变量,这将导致重新呈现您期望的值。 这样做的问题是,即使传递给它的props没有改变, Banner组件也会重新渲染。

To circumvent this, we use memo which acts like PureComponent in the fact that it will stop re-renders when the props haven’t changed. Our code updated looks like:

为了避免这种情况,我们使用memo ,它的作用类似于PureComponent ,因为当props没有变化时,它将停止重新渲染。 我们更新的代码如下所示:

const Banner = memo(props => {
  const { type } = props;

  if (type === "info") {
    return <div className="info-banner">I am an info banner</div>;
  }
});

Now our Banner component will only re-render when the props to it have changed.

现在,我们的Banner组件仅在其props更改时才会重新渲染。

This is core fundamental idea of React memo.

这是React备忘录的核心基本思想。

平等 (areEqual)

Ok so let’s get a little more advanced and talk about custom equality. By default, memo only does a shallow comparison of props and prop’s objects. You can pass a second argument to indicate a custom equality check:

好吧,让我们更进一步,讨论自定义相等性。 默认情况下, memo仅对道具和道具的对象进行shallow比较。 您可以传递第二个参数来指示自定义相等性检查:

React.memo(Component, [areEqual(prevProps, nextProps)]);

This is similar to shouldComponentUpdate but the inverse i.e. returning true in shouldComponentUpdate causes another render whereas areEqual is the opposite.

这类似于shouldComponentUpdate但是相反,即在shouldComponentUpdate返回true会导致另一个渲染,而areEqual相反。

Imagine we had a Person component that accepted a prop person which is an object, we could check if the name is the same.

想象一下,我们有一个Person组件,它接受了作为对象的prop person,我们可以检查name是否相同。

const areEqual = (prevProps, nextProps) => {
  return (prevProps.name === nextProps.name)
};
React.memo(Person, areEqual);

结论 (Conclusion)

This is a really nice addition to React, allowing us to use functional components without having the worry about needless re-renders. As always, I hope you learned something good with this post!

这是对React的一个非常好的补充,它使我们能够使用功能组件,而不必担心不必要的重新渲染。 与往常一样,我希望您从这篇文章中学到了好东西!

翻译自: https://www.digitalocean.com/community/tutorials/react-learning-react-memo

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值