Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
535 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...