【问题标题】:ReactJS Intersection Observer only working once if I change something in App.tsx... if I refresh the browser, it will not work work anymore如果我在 App.tsx 中更改某些内容,ReactJS Intersection Observer 仅工作一次......如果我刷新浏览器,它将不再工作
【发布时间】:2022-06-10 22:18:05
【问题描述】:

我面临一个问题,即只有在我更改了 App.tsx 中的某些内容并通过“ctrl+s”保存后,交叉点观察器才起作用 应用程序.tsx:


    import React, {
      lazy,
      RefObject,
      Suspense,
      useState,
      useEffect,
      ReactElement,
      useRef,
      FunctionComponent,
    } from "react"
    
    import "./App.css"
    import Navbar from "./components/Navbar/Navbar"
    import Hero from "./components/Hero/Hero"
    import { useElementOnScreen } from "./hooks/useElementOnScreen"
    import { LegacyRef } from "react"
    // const SkillList = lazy(() => import("./components/SkillList/SkillList"))
    import SkillList from "./components/SkillList/SkillList"
    
    const App: FunctionComponent = (): ReactElement => {
      const options = {
        threshold: 0,
      }
      const refComp = useRef<Element>(null)
      const isVisible = useElementOnScreen(refComp, options)
    
      return (
        <div>
          <Navbar />
          <Hero />
          <div>neuer component</div>
          <Suspense fallback={<div>Loading...</div>}>
            <div ref={refComp as LegacyRef<HTMLDivElement>}>
              {isVisible && <SkillList />}
            </div>
          </Suspense>
        </div>
      )
    }

export default App

然后似乎一切正常。这是一个屏幕截图: react intersection observer triggered

一旦我刷新浏览器,它将不再被触发。我必须再次更改 App.tsx,然后它会再次触发。这是为什么呢?

这是我在 App.tsx 中使用的钩子

``

import React, { createRef } from "react"
import {
  useRef,
  useState,
  useEffect,
  RefObject,
  useMemo,
  LegacyRef,
} from "react"

interface OptionsI {
  threshold: number
}
export const useElementOnScreen = (
  ref: RefObject<Element>,
  options: OptionsI
) => {
  const [isVisible, setIsVisible] = useState(false)
  console.log(isVisible)

  // const optionsMemo = useMemo(() => {
  //   return options
  // }, [options])
  const containerRef = ref.current
  useEffect(() => {
    const observer = new IntersectionObserver((entries) => {
      const [entry] = entries
      console.log(entry)
      setIsVisible(entry.isIntersecting)
      console.log("ISSS")
    }, options)

    if (containerRef) observer.observe(containerRef)

    return () => {
      if (containerRef) observer.unobserve(containerRef)
    }
  })

  return isVisible
}

我想要实现的是延迟加载组件,一旦它的容器 div 在视图中。

【问题讨论】:

    标签: reactjs intersection-observer react-intersection-observer


    【解决方案1】:

    我也面临同样的问题。你找到解决办法了吗?

    【讨论】:

    猜你喜欢
    • 2018-04-25
    • 2018-09-17
    • 2016-10-19
    • 1970-01-01
    • 2020-02-27
    • 2021-10-24
    • 1970-01-01
    • 2017-06-02
    • 2017-11-22
    相关资源
    最近更新 更多