如何将IntersectionObserver与React结合使用



我目前有一个包含多个功能的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时,我建议使用为其创建的钩子,如useInView。

最新更新