简体   繁体   English

当依赖项是 object 时,如何使用 useCallback、useMemo 和 React.memo?

[英]How to use useCallback, useMemo and React.memo when dependency is an object?

I have useMemo when one of its dependencies is an Object that I get from the server, so even when the content of the object is the same - the useMemo is called over and over again in each sync from the server because the object itself is different every time, of course it is the same for useCallback and React.memo .当它的一个依赖项是我从服务器获得的Object时,我有useMemo ,所以即使 object 的内容相同 - 由于useMemo本身不同,因此在每次同步中从服务器一次又一次调用 useMemo每次,当然useCallbackReact.memo一样的。

How can I solve this?我该如何解决这个问题?

I was thinking about checking manually if the new result has the same contents as the previous result and if it does - stay with the previous object reference.我正在考虑手动检查新结果是否与之前的结果具有相同的内容,如果确实如此 - 请使用之前的 object 参考。

Two options really:真的有两个选择:

  • do as you planned, ie don't change the object if it's deep-equal (eg deep-equal on npm ) to the object you receive:按照您的计划进行,即如果 object 深度相等(例如npm 上的deep-equal ),则不要将 object 更改为您收到的 object:
     const [obj, setObj] = React.useState(); //... const newObj = await getObjectFromServer(); // Using the function form of setState to avoid races and an extra // dependency on `obj`: setObj(oldObj => equal(newObj, oldObj)? oldObj: newObj);
  • depend on the fields the memo uses, not the full object:取决于memo使用的字段,而不是完整的 object:
    • Not this:不是这个:
       React.useMemo(() => obj.foo + 8, [obj]);
    • But this:但是这个:
       React.useMemo(() => obj.foo + 8, [obj.foo]);
    However, that may easily get cumbersome and won't help if obj.foo itself is not a primitive.但是,如果obj.foo本身不是原语,这可能很容易变得麻烦并且无济于事。

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

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