javascript - 如何将 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。
推荐阅读
- python - 如何在 Django 项目中创建 requirements.txt 文件?
- html - 使用 rvest(或另一个 R 包)来检测 HTML 段落的开头何时是不同的格式(例如加粗)
- python - 如何在多索引数据框中按第二级的日期切片进行过滤
- python - 使用 opencv-python 将一批帧保存为视频
- python - 用于许多可能字符串的 Python .contains() 函数
- mongodb - Mongoose 事务 session.withTransaction 不是函数
- hyperledger - 组织,应用。订购者。配置文件中的频道。如何设计它?
- python - 如何在 Python 中使用 lxml 将元素内的任何内容与另一个元素一起包装?
- python - 有没有办法使用 discord.py 从 python 的 IDE 发送消息?
- spring - Spring Secuirty SAML2 Core - 为运行时创建的身份提供者添加密钥