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> ); };