我們可以使用瀏覽器提供的 IntersectionObserver API 來實現無限滾動。
要實施,我們只需按照以下步驟操作:-
CustomHook.jsx
import axios from "axios"; import { useEffect, useState } from "react"; import { API_URL } from "../common/constants"; export const useAuthorList = (limit, page) => { const [isLoading, setIsLoading] = useState(false); const [authorList, setAuthorList] = useState([]); const [error, setError] = useState(""); const [hasMore, setHasMore] = useState(true); useEffect(() => { setIsLoading(true); setTimeout(() => { axios({ method: "GET", url: API_URL, params: { limit: limit, page: page }, }) .then((res) => { setAuthorList(res.data.data); setHasMore(res.data.data.length === limit); setIsLoading(false); }) .catch((e) => setError(e)); }, 500); }, [limit, page]); return [isLoading, authorList, error, hasMore]; };
App.jsx
import React, { useCallback, useRef, useState } from "react"; import { useAuthorList } from "./hooks/useAuthorList"; import { AuthorQuotes } from "./components/AuthorQuotes"; const App = () => { const [limit, setLimit] = useState(10); const [page, setPage] = useState(1); const [isLoading, authorList, error, hasMore] = useAuthorList(limit, page); const observer = useRef(null); const infiniteReference = useCallback( (element) => { if (isLoading) return; if (observer.current) { observer.current.disconnect(); } observer.current = new IntersectionObserver((entries) => { if (entries[0].isIntersecting && hasMore) { setLimit((prev) => prev + 10); } }); if (element) { observer.current.observe(element); } }, [isLoading, hasMore] ); return ( <div className="author-quotes-list"> {authorList.length > 0 && authorList.map((authorQuotes, index) => { if (index + 1 === authorList.length) { return ( <AuthorQuotes authorQuotes={authorQuotes} hasReference infiniteReference={infiniteReference} /> ); } return <AuthorQuotes authorQuotes={authorQuotes} />; })} {isLoading && <>Loading...</>} </div> ); }; export default App;
constants.js
export const API_URL = "https://api.javascripttutorial.net/v1/quotes/"
以上是透過簡單的步驟掌握無限滾動的詳細內容。更多資訊請關注PHP中文網其他相關文章!