您好,我正在開發一個頁面,該頁面從 sanity.io 資料存儲中提取項目列表,並嘗試使用無限滾動一次顯示 10 個項目,以便在每次項目下降時再渲染 10 個項目。但是,我遇到的問題是僅顯示前 10 個項目,並且似乎沒有呼叫 fetchNextPages 函數。我已經在這個問題上絞盡腦汁好幾個小時了,感謝任何幫助
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 } 從 "../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
嘿,請更改您的程式碼-
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); };
這個..因為我認為你的 fetchNextPage 有問題-
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); };
請告訴我這是否有效。我會幫你更多..!