使用 useMemo 而不是 React.memo 语法问题 [英] Using useMemo instead of React.memo syntax issue

查看:111
本文介绍了使用 useMemo 而不是 React.memo 语法问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要演示一下如何使用 React Hooks useMemo.我有如下工作代码,可以满足我的要求:

I need to make a demonstration of using React Hooks useMemo. I have working code that is as follows that does what I want:

const SpeakerCardDetail = React.memo(
  ({id,...

我发现了一个 link 表明我可以使用更像这样的语法,但我完全搞不清楚.

I found a link that shows that I could use syntax more like this but I can't figure it out exactly.

这是我得到的:

const SpeakerDetail = React.useMemo(() => {
   ({ id,

显然不是.我确实知道 React.memo 解决了这个问题,但我确实需要展示 useMemo 的实际效果,并希望有一种我可以使用的替代语法.

Clearly not it though. I do get that React.memo solves the problem but I do need to show useMemo in action and am hoping there is an alternative syntax that I can use.

推荐答案

React.memoReact.useMemo 根本不等价(不要依赖命名相似).这里引用了 React.memo doc:

React.memo and React.useMemo are not equivalent at all (don't rely on naming similarity). Here's a quote from React.memo doc:

React.memo 是一个高阶组件.

因此,它是一个 HOC,可以优化组件的呈现,因为它使用相同的属性呈现相同的输出.

So it's a HOC that can optimize rendition of your component given that it renders the same output with the same properties.

React.useMemo 另一方面更通用,返回一个记忆值:

传递一个创建"函数和一组依赖项.useMemo 将仅当依赖项之一(ab)具有时才重新计算记忆值改变了.

Pass a "create" function and an array of dependencies. useMemo will only recompute the memoized value when one of the dependencies (either a or b) has changed.

const memoizedValue = useMemo(
  () => computeExpensiveValue(a, b), 
  [a, b]
);

虽然它可以被破解以代替 React.memo 使用,但这不是它的目的,它只会增加混乱而不是帮助.useMemo 是一个钩子,受某些使用规则的约束.

And while it can be hacked to be used instead of React.memo, it's not its purpose and it will add to the confusion more than it will help. useMemo is a hook and is subject to the certain usage rules.

还有这个警告:

在未来,React 可能会选择忘记"一些之前记忆的值并在下一次渲染时重新计算它们,例如释放内存离屏组件.编写您的代码,使其在没有useMemo — 然后添加它以优化性能.

In the future, React may choose to "forget" some previously memoized values and recalculate them on next render, e.g. to free memory for offscreen components. Write your code so that it still works without useMemo — and then add it to optimize performance.

这篇关于使用 useMemo 而不是 React.memo 语法问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆