简体   繁体   English

在 useEffect 钩子上获取无限循环

[英]Getting infinite loop on useEffect hook

Trying to build a tooltip component.试图构建一个工具提示组件。 When the tooltip moves away from the viewport need to switch the tooltip position that is working fine.当工具提示从视口移开时,需要切换工作正常的工具提示 position。 But when the tooltip is away from the viewport useEffect running infinitely.但是当工具提示远离视口时,useEffect 会无限运行。 cant able to find the root cause.无法找到根本原因。

Adding sandbox link https://codesandbox.io/s/dbpkr添加沙箱链接https://codesandbox.io/s/dbpkr

Try using a dependency array尝试使用依赖数组

useEffect(() => {;
    let intersectionObserver = new IntersectionObserver(function (entries) {
      if (!entries[0].isIntersecting) {
        setMoveBottom(!moveBottom);
      }
    });

    if (refElement) intersectionObserver.observe(refElement);

    return () => {
      if (refElement) intersectionObserver.unobserve(refElement);
    };
  }, [setMoveBottom, moveBottom, refElement]);

Yeah because you are not passing dependency for useEffect hook.是的,因为您没有传递 useEffect 挂钩的依赖项。

So add either empty array or pass any dependencies by end of the useEffect因此,在 useEffect 末尾添加空数组或传递任何依赖项

Eg:例如:

 useEffect(() => {


}, [])

for more info read this enter link description here有关更多信息,请阅读此处在此处输入链接描述

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

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