React 中的清理引用问题

Jos*_*eph 20 reactjs eslint react-hooks

我遇到问题,导致 ESLINT 在控制台中输出错误。我想解决控制台中的问题。请在此处检查代码和框

点击这里

更新问题

The 'callbackFunction' function makes the dependencies of useEffect Hook (at line 33) change on every render. Move it inside the useEffect callback. Alternatively, wrap the definition of 'callbackFunction' in its own useCallback() Hook. (react-hooks/exhaustive-deps)
Run Code Online (Sandbox Code Playgroud)

老问题

The ref value 'containerRef.current' will likely have changed by the time this effect cleanup function runs. If this ref points to a node rendered by React, copy 'containerRef.current' to a variable inside the effect, and use that variable in the cleanup function. (react-hooks/exhaustive-deps)
eslint

React Hook useEffect has a missing dependency: 'callbackFunction'. Either include it or remove the dependency array. (react-hooks/exhaustive-deps)
Run Code Online (Sandbox Code Playgroud)

代码

  useEffect(() => {
    const observer = new IntersectionObserver(callbackFunction, options);
    if (containerRef.current) observer.observe(containerRef.current);

    return () => {
      if (containerRef.current) observer.unobserve(containerRef.current);
    };
  }, [containerRef, options]);
Run Code Online (Sandbox Code Playgroud)

Dre*_*ese 20

containerRef.current在此效果清理函数运行时,参考值可能已发生变化。如果此 ref 指向 React 渲染的节点,则复制containerRef.current到效果内的变量,并在清理函数中使用该变量。(反应钩子/详尽的依赖)

只需将当前引用值保存到本地范围的变量中,即可在效果的清理函数中关闭。

React HookuseEffect缺少依赖项:callbackFunction. 包含它或删除依赖项数组。(反应钩子/详尽的依赖)

当值更新时(如果有的话),您将需要清理所有旧的订阅观察者、引用、回调等callbackFunction。将其添加到依赖项数组中。

useEffect(() => {
  let observerRefValue = null; // <-- variable to hold ref value

  const observer = new IntersectionObserver(callbackFunction, options);

  if (containerRef.current) {
    observer.observe(containerRef.current);
    observerRefValue = containerRef.current; // <-- save ref value
  }

  return () => {
    if (observerRefValue) observer.unobserve(observerRefValue); // <-- use saved value
  };
}, [callbackFunction, options]);
Run Code Online (Sandbox Code Playgroud)

更新

“callbackFunction”函数使 useEffect Hook(第 33 行)的依赖关系在每次渲染时都会发生变化。将其移至 useEffect 回调内。或者,将“callbackFunction”的定义包装在其自己的 useCallback() Hook 中。(反应钩子/详尽的依赖)

您可以通过包装在useCallback钩子中来记住此回调:

const callbackFunction = React.useCallback((entries) => {
  const [entry] = entries;
  onIntersection(video.id, entry);
}, [onIntersection, video]);
Run Code Online (Sandbox Code Playgroud)

或者您可以简单地将回调移动挂钩中useEffect并更新依赖项:

useEffect(() => {
  const callbackFunction = (entries) => {
    const [entry] = entries;
    onIntersection(video.id, entry);
  };

  let observerRefValue = null;

  const observer = new IntersectionObserver(callbackFunction, options);

  if (containerRef.current) {
    observer.observe(containerRef.current);
    observerRefValue = containerRef.current;
  }

  return () => {
    if (observerRefValue) observer.unobserve(observerRefValue);
  };
}, [onIntersection, options, video]);
Run Code Online (Sandbox Code Playgroud)