javascript - 如何将 IntersectionObserver 与 React 结合使用?

标签 javascript reactjs use-effect intersection-observer

我目前有一个 useEffect,其中包含多个函数。我决定创建无限滚动功能,但我很难实现它:

这就是我所拥有的:

const [posts, setPosts] = useState([]);
const [page, setPage] = useState(1);
const ref = { current: null };
useEffect(() => {
  getPosts(params).then((result) => {
    setPosts(result);
  }).catch((err) => {});
  ...
  ...
  ...
  const observer = new IntersectionObserver((entries) => {
    if (entries[0].isIntersecting) {
      setPage(next);
    }
  }, {
    threshold: 0.1
  }
                                           );
  observer.observe(ref.current);
}, [getPosts, ..., ..., ref])

/// FETCHED POSTS
{posts?.length > 0 ? (
  posts.map((post, index) => (
    <Single
        key={post._id}
        post={post}
        postId={postId}
        setObjects={setPosts}
        objects={posts}
        setTotalResult={setTotalResults}
    />
  ))
) : (
  <NothingFoundAlert />
)}
/// BUTTON
<button ref={ref} style={{ opacity: 0 }}>
    Load more
</button>

无论我做什么,它都会抛出此错误:

TypeError: Failed to execute 'observe' on 'IntersectionObserver': parameter 1 is not of type 'Element'.

以前有人用过这个吗?

最佳答案

const ref = { current: null }
// to
const ref = useRef()

应该解决该问题,因为错误表明您正在尝试观察分配的 null 而不是 HTMLElement。

在 React 中使用 IntersectionObserver 时,我建议使用为其创建的钩子(Hook),例如 useInView .

关于javascript - 如何将 IntersectionObserver 与 React 结合使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66611737/

相关文章:

javascript - 使用函数切换 bool 值?

JavaScript 逻辑运算符 : multiple || syntax dilemma

reactjs - 使用 axios 发出的请求不起作用,但如果它适用于 XMLHttpRequest

javascript - 从函数中提取 props 到 React 中的组件中

javascript - 时间总是成为纪元时间并且超出域范围

javascript - 如何使用 vuejs 避免重复的 websocket 客户端

javascript - 使用 nextjs 放大时,React Image Magnifiers 不起作用

reactjs - typescript 中的 ChartJs 图表 : Object is possibly undefined in useEffect

reactjs - Prop 更改不会触发 useEffect

javascript - 为什么 react-native-onboarding-swiper 不能在我的启动画面上工作?