我们可以使用浏览器提供的 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 ({authorList.length > 0 && authorList.map((authorQuotes, index) => { if (index + 1 === authorList.length) { return (); }; export default App;); } return ; })} {isLoading && <>Loading...>}
constants.js
export const API_URL = "https://api.javascripttutorial.net/v1/quotes/"
以上是通过简单的步骤掌握无限滚动的详细内容。更多信息请关注PHP中文网其他相关文章!