P粉3232241292023-08-29 15:51:44
为了实现这个目标,您需要两个组件。
Intersection Observer API
的交互,您应该使用来自react-intersection-observer
库的useInView
钩子。
import React from 'react'; import { useQuery } from "react-query"; import { useInView } from "react-intersection-observer"; const PostComponent = ({ post }) => { const { ref, inView } = useInView(); const { data, isLoading, error } = useQuery( ["comments", post.id], () => fetchComments(post.id), // the useQuery hook will fetch only when inView is enabled { enabled: inView } ); return ( <div ref={ref}> {isLoading && <div>Loading comments...</div>} {error && <div>Error fetching comments</div>} {data && ( <div> <p>{post.title}</p>{" "} </div> )} </div> ); };