在 React.useEffect 中取消观察 IntersectionObserver

Dar*_*ren 4 javascript observable reactjs

我正在尝试使用 来获取多个元素的top和测量值。然而,一旦我有了测量结果,我该如何测量元素呢?bottomIntersectionObserverunobserve

问题是每个元素都是,position: sticky并且当滚动时附加值被添加到,array并且我只想要初始渲染的测量值。

const observer = new IntersectionObserver((entries) => {
    entries.forEach((entry) => {
      const measurement = {
        top: entry.boundingClientRect.top,
        bottom: entry.boundingClientRect.bottom,
      };
      console.log(measurement);
    });
  });

  useEffect(() => {
    const sections = document.querySelectorAll(`section#dark`)
    sections.forEach((section) => observer.observe(section));
    return () => {
      // observer.disconnect(); removed in Stackoverflow edit
      sections.forEach(section => observer.observe(section)); // Added in Stackoverflow edit
    };
  }, []);
Run Code Online (Sandbox Code Playgroud)

我尝试过使用observer.unobserve(),但无法弄清楚它需要什么值,因为它返回一个错误Argument of type 'NodeListOf<Element>' is not assignable to parameter of type 'Element'.

编辑:我想出了如何使用oberver.unobservewithsections.forEach(section => observer.unobserve(section));但它在滚动时仍然会添加更多记录。

完整的例子可以在这里看到StackBlitz

lis*_*tdm 5

您需要将观察者实例移动到useEffect阻止,因为每次更新组件时IntersectionObserver 都会创建一个新实例:

useEffect(() => {
  const observer = new IntersectionObserver((entries) => {
      entries.forEach((entry) => {
      const measurement = {
        top: entry.boundingClientRect.top,
        bottom: entry.boundingClientRect.bottom,
      };
      console.log(measurement);
      observer.unobserve(entry.target); //<-- call unobserve here
      });
    });
  const sections = document.querySelectorAll(`section#dark`)
  sections.forEach((section) => observer.observe(section));
  return () => {
     observer.disconnect();
  };
}, []);
Run Code Online (Sandbox Code Playgroud)