useCallBack 和 useEffect 无限循环 [英] useCallBack and useEffect infinite loop

查看:45
本文介绍了useCallBack 和 useEffect 无限循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据下面的代码,我需要在 inView 为真时调用一个函数,但是使用 useEffectuseCallback 列出依赖项,我导致无限循环.我设法避免它的唯一方法是不列出依赖项,但我收到警告,我必须列出它们.我只尝试了 useEffect,但结果是一样的,列出依赖项,循环有问题.代码如下:

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. 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. 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

推荐答案

无限循环最可能的原因是 onEnterView.为确保这是原因,请向我们展示该函数的创建位置.我认为会发生什么(我有 99.99% 的把握)是您在某个父级中创建了一个箭头函数(没有将它包装在 useCallback 中).调用 onEnterView 使该父级重新呈现(您说您调用了 dispatch) ,这也意味着 onEnterView 函数的引用将更改.结果是你每次调用 useLazyLoader 钩子时都会得到一个新的 onEnterView,所以你在那里的 useCallback 几乎没用(你每次都会得到不同的依赖,所以他重新创建了 useCallback 结果).要解决您的问题,请将 onEnterView 包装在 useCallback 中定义的位置,而不是使用的位置.

The most probable reason for your infinite loop is 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). Calling onEnterView makes that parent re-render (you said you called dispatch) , which also mean the onEnterView function's reference will change. 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). To fix your problem, please wrap the onEnterView in useCallback where is defined, rather than where it is used.

这篇关于useCallBack 和 useEffect 无限循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆