简体   繁体   English

React useMemo hook memoize 是否应该使用相同的依赖值重复调用?

[英]Should the React useMemo hook memoize repeat calls with same dependency values?

I have an issue where a (fake) long running / expensive function inside a functional component doesn't appear to be memoized how I would think it would be.我有一个问题,即功能组件内的(假的)长时间运行/昂贵的 function 似乎没有被记住我的想法。

From my understanding of memoization, calling a memoized function with the same param value would simply return the result of the previous call.根据我对 memoization 的理解,使用相同的参数值调用 memoized function 只会返回上一次调用的结果。

That is ONLY happening with useMemo (in my app at least) when values on the component change that are not in the dependencies list.仅当组件上的值更改不在依赖项列表中时,useMemo(至少在我的应用程序中)才会发生这种情况。 I get that different values would need to rerun the expensive function again, but even if I call the function with a previously used value (value / primitive types, not reference types / objects), it re runs the expensive function again.我知道不同的值需要再次运行昂贵的 function,但即使我用以前使用的值(值/原始类型,而不是引用类型/对象)调用 function,它也会再次运行昂贵的 ZC1C425268E68384F1。

Either I've not got something quite right or my understanding of what useMemo does isn't quite right (is this where React.memo comes in?).要么我没有完全正确,要么我对 useMemo 所做的理解不太正确(这就是 React.memo 的用武之地吗?)。

This can be seen in this rudimentary stackblitz .这可以在这个基本的stackblitz中看到。

Could anyone tell me where I'm going wrong please.谁能告诉我我要去哪里错了。

What are you thinking is you can say 50% correct.你在想什么,你可以说 50% 正确。

useMemo does not execute the code again for same set of parameters, but useMemo不会为同一组参数再次执行代码,但

It only remembers last value of parameters.它只记住参数的最后一个值。

In your example, when you are clicking + and - button, you are changing value of value from previous value.在您的示例中,当您单击 + 和 - 按钮时,您正在从以前的值更改值的value On 2nd click if you are coming back to same value, it does not mean memoize will return value wothout executing the function.在第二次单击时,如果您返回相同的值,这并不意味着 memoize 将返回值而不执行 function。

Try to add a button and on click on it set same current value setValue(value) , you will see there is not recalculation happening.尝试添加一个按钮并单击它设置相同的当前值setValue(value) ,您将看到没有重新计算发生。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM