【问题标题】:How to use IntersectionObserver with React?如何将 IntersectionObserver 与 React 一起使用?
【发布时间】:2021-03-13 09:05:34
【问题描述】:

我目前有一个包含多个功能的 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 }; 更改为 const ref = useRef(null) 并将整个 IntersectionObserver 子句包含在 if (ref.current) 条件中

标签: javascript reactjs use-effect intersection-observer


【解决方案1】:
const ref = { current: null }
// to
const ref = useRef()

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

在 React 中使用 IntersectionObserver 时,我建议使用为它创建的钩子,例如 useInView

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-30
    • 2016-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-09
    • 2021-04-13
    相关资源
    最近更新 更多