您好,我正在开发一个页面,该页面从 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 } 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;
嘿,请更改您的代码-