繁体   English   中英

如何在 React 中使用 useMemo 优化我的代码?

[英]How to optimize my code with useMemo in React?

我在 React 中useMemo()useMemo()钩子的情况。

我有一个名为a的数组对象。 此对象包含多个对象。 这个数组很大。 当它包含bc对象时, a看起来像a = [b,c] 我正在对数组a进行大量计算。 这是我的代码片段:

    const computedValue = useMemo(() => {
         return a.map(key,() => {
           anotherHighComputationFunc(key);
         });
    },[a])

const anotherHighComputationFunc = useMemo((key) => {
        // ..... do some expensive computation
       return someValue;
},[key]);

如果一个参考a不改变,我不要再计算的价值,我只是返回预先计算值。 如果一个参考a变化,然后我会看看到数组a检查,如果一些关键的,改变了对阵列内部参考。 如果某个键的引用没有改变,则返回该键的预计算值,否则对该键进行计算。

问题是钩子规则失败了,因为我在另一个钩子中使用了一个钩子。 所以它给我一个错误。 有没有其他方法可以在 2 个级别进行记忆?

useMemo()钩子在这里对您没有帮助,因为它的缓存大小为 1,并且您不能在其他钩子中调用钩子。 此外,您不需要记住函数,而是记住调用的结果。

您可以使用WeakMap创建一个简单的记忆包装器,这将允许垃圾收集器在不需要时清理值。

注意:WeakMap 键必须是对象。

const weakMemo = fn => {
  const map = new WeakMap();
  
  return obj => {
    if (map.has(obj)) return map.get(obj);
    
    const res = fn(obj);
    
    map.set(obj, res);
    
    return rs;
  }
};

// the useMemo is needed here to preserve the instance of the memoized function with the cached values
const computeKey = useMemo(() => weakMemo((key) => {
  // ..... do some expensive computation
  return someValue;
}), [anotherHighComputationFunc]);

const computedValue = useMemo(() => a.map(computeKey), [a, computeKey]);

Hooks 的规则明确规定:不要在循环、条件或嵌套函数中调用 Hooks。 相反,始终在 React 函数的顶层使用 Hook。

与其为您的anotherHighComputationFunc使用钩子,不如创建一个cache对象,该对象存储函数的值并在它位于缓存对象内部时返回它。

const cache = {};

function anotherHighComputationFunc(key) {
   if (cache[key]) return cache[key];

    /** anotherHighComputation calculation here */
    cache[key] = anotherHighComputationValue;
    return anotherHighComputationValue
} 

 const computedValue = useMemo(() => {
     return a.map(key,() => {
       anotherHighComputationFunc(key);
    });
},[a])

暂无
暂无

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

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