Rumah > Soal Jawab > teks badan
Hai, saya sedang membangunkan halaman yang menarik senarai item dari stor data sanity.io dan cuba memaparkan 10 item pada satu masa menggunakan skrol tak terhingga supaya setiap kali item jatuh, 10 item lagi dipaparkan. Walau bagaimanapun, masalah yang saya hadapi ialah hanya 10 item pertama dipaparkan dan fungsi fetchNextPages nampaknya tidak dipanggil. Saya telah memerah otak saya tentang isu ini selama berjam-jam sekarang, sebarang bantuan adalah dihargai
import React, { useState, useEffect } from "react"; import { useParams } from "react-router-dom"; import { client } from "../client"; import MasonryLayout from "./MasonryLayout"; import Spinner from "./Spinner"; import { feedQuery, searchQuery } from "../utils/data"; import InfiniteScroll from "react-infinite-scroll-component"; const Feed = () => { const [loading, setLoading] = useState(false); const { categoryId } = useParams(); const [items, setItems] = useState(null); const [pages, setPages] = useState([]); const [firstId, setFirstId] = useState(10); const [lastId, setLastId] = useState(20); const [hasMore, setHasMore] = useState(true); useEffect(() => { setLoading(true); if (categoryId) { const query = searchQuery(categoryId); client.fetch(query).then((data) => { setItems(data); setLoading(false); }); } else { client.fetch(feedQuery).then((data) => { setItems(data); setLoading(false); }); } }, [categoryId]); useEffect(() => { setPages(items?.slice(0, 10)); }, [items]); const fetchNextPage = () => { const result = items.slice(firstId, lastId); setPages([...pages, ...result]); if (result.length===0 || result.length < 10) { setHasMore(false); } setFirstId(firstId + 10); setLastId(lastId + 10); }; if (loading) return <Spinner message="Searching for items...!" />; if (!pages?.length) return <h2>No results available.</h2>; return ( <InfiniteScroll dataLength={pages?.length} next={fetchNextPage} hasMore={hasMore} loader={ <Spinner message="Searching for items..." endMessage={ <p className="align-center font-extrabold">End of list.</p> } /> } > <div> <div className="mt-4 bm-4 w-full rounded overflow-hidden shadow-lg bg-slate-50 pl-2 pr-2 pt-4 pb-4"> <p>Some information about this … </p> </div> {pages && <MasonryLayout items={pages} />} </div> </InfiniteScroll> ); }; export default Feed;
P粉7454121162024-02-27 09:06:37
Hey sila tukar kod anda-
const fetchNextPage = () => { const result = items.slice(firstId, lastId); setPages([...pages, ...result]); if (result.length===0 || result.length < 10) { setHasMore(false); } setFirstId(firstId + 10); setLastId(lastId + 10); };
Ini..kerana saya rasa ada yang tidak kena dengan fetchNextPage anda -
const fetchNextPage = () => { const result = items.slice(firstId, lastId + 10); setPages([...pages, ...result]); if (result.length === 0 || result.length < 10) { setHasMore(false); } setFirstId(lastId + 1); setLastId(lastId + 10); };
Sila beritahu saya jika ini berkesan. Saya akan bantu anda lagi..!