
Nous pouvons implémenter un défilement infini en utilisant l'API IntersectionObserver fournie par le navigateur.
Pour mettre en œuvre, nous pouvons simplement suivre ces étapes :-
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 ( ); } return ; })} {isLoading && <>Loading...>} ); }; export default App;
constantes.js
export const API_URL = "https://api.javascripttutorial.net/v1/quotes/"
Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!
Téléphone portable projecteur
Comment ajuster la taille du texte dans les messages texte
Apple Pay ne peut pas ajouter de carte
Comment empêcher l'ordinateur d'installer automatiquement le logiciel
Qu'est-ce que le courrier électronique
A quoi sert le dossier itinérant ?
solution de chemin fakepath
L'ordinateur portable n'a soudainement plus d'option WLAN