Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
566 views
in Technique[技术] by (71.8m points)

ref 需不需要作为依赖参数传给 useCallback 或者 useMemo

问题描述

在 react 官网的 Hooks FAQ 中有一些关于 useCallback 用法的例子,比如自定义的 useEventCallback 函数,其中会在 useCallback 的依赖参数中加入 ref。

可是 useRef 返回的 ref 不是在函数式组件的生命周期中都不会发生引用上的变化吗,为什么还要作为依赖参数加入呢?

相关代码

function useEventCallback(fn, dependencies) {
  const ref = useRef(() => {
    throw new Error('Cannot call an event handler while rendering.');
  });

  useEffect(() => {
    ref.current = fn;
  }, [fn, ...dependencies]);

  return useCallback(() => {
    const fn = ref.current;
    return fn();
  }, [ref]);
}

想问问各位大佬们 ref 作为依赖参数的意义,以及什么时候场景下会有 ref 的变更?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神解答

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...