您好,我正在开发一个页面,该页面从 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 ;
if (!pages?.length) return No results available.
;
return (
End of list.
}
/>
}
>
Some information about this …
{pages && }
);
};
export default Feed;
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
嘿,请更改您的代码-
const fetchNextPage = () => { const result = items.slice(firstId, lastId); setPages([...pages, ...result]); if (result.length===0 || result.length这个..因为我认为你的 fetchNextPage 有问题-
const fetchNextPage = () => { const result = items.slice(firstId, lastId + 10); setPages([...pages, ...result]); if (result.length === 0 || result.length请告诉我这是否有效。我会帮助你更多..!