简体   繁体   English

useCallBack 和 useEffect 无限循环

[英]useCallBack and useEffect infinite loop

According to the code below, I need to call a function whenever inView is true, but using useEffect and useCallback listing the dependencies, I cause an infinite loop.根据下面的代码,每当inView为 true 时,我都需要调用一个函数,但是使用useEffectuseCallback列出依赖项,我会导致无限循环。 The only ways I managed to avoid it were without listing the dependencies, but I get a warning that I have to list them.我设法避免它的唯一方法是不列出依赖项,但我收到警告,我必须列出它们。 I tried only with useEffect , but the result is the same, listing the dependencies, I have a problem with the loops.我只尝试了useEffect ,但结果是一样的,列出了依赖项,循环有问题。 Here is the code:这是代码:

import { useEffect, useCallback } from "react";
import { useInView } from "react-intersection-observer";

export const useLazyLoader = (onEnterView: () => void) => {
  const [ref, inView] = useInView({
    triggerOnce: true,
    rootMargin: "-200px",
  });

  const innerEnterView = useCallback(() => {
    onEnterView();
  }, [onEnterView]);

  useEffect(() => {
    inView && innerEnterView();
  }, [inView, innerEnterView]);
  return ref;
};

In this example, if I remove any of the dependencies to try to avoid the problem, I end up getting the warning like this:在这个例子中,如果我删除任何依赖项来试图避免这个问题,我最终会收到这样的警告:

Line 16:6:  React Hook useEffect has a missing dependency: 'innerEnterView'. Either include it or remove the dependency array  react-hooks/exhaustive-deps

The most probable reason for your infinite loop is onEnterView.无限循环最可能的原因是 onEnterView。 To make sure that is the cause, please show us where that function is created.为确保这是原因,请向我们展示该函数的创建位置。 What I think it happens (and I am 99.99% sure about it) is you create an arrow function in some parent (without wrapping it in useCallback).我认为会发生什么(我有 99.99% 的把握)是您在某个父级中创建了一个箭头函数(没有将它包装在 useCallback 中)。 Calling onEnterView makes that parent re-render (you said you called dispatch) , which also mean the onEnterView function's reference will change.调用 onEnterView 使该父级重新呈现(您说您调用了 dispatch) ,这也意味着 onEnterView 函数的引用将更改。 The result is you get a new onEnterView every time you call useLazyLoader hook, so the useCallback you have in place there is pretty much useless (you get a different dependency every time, so he recreates the useCallback result).结果是你每次调用 useLazyLoader 钩子时都会得到一个新的 onEnterView,所以你在那里的 useCallback 几乎没用(你每次都会得到不同的依赖,所以他重新创建了 useCallback 结果)。 To fix your problem, please wrap the onEnterView in useCallback where is defined, rather than where it is used.要解决您的问题,请将 onEnterView 包装在 useCallback 中定义的位置,而不是使用它的位置。

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

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