[英]Infinite scrolling and updating it with newly fetched data in React
我正在尝试渲染一个无限滚动组件,并在滚动到它的末尾时用新获取的新闻更新它的数据。 它适用于第一个卷轴,但卡在Loading...
之后。 我不明白是什么导致它在第一次滚动后停止获取。
应该获取新数据的代码如下所示:
const [latestNews, setLatestNews] = useState<any[]>([]);
const [page, setPage] = useState<number>(1);
const getLatestNews = async (page: number) => {
let url = `https://api.nytimes.com/svc/search/v2/articlesearch.json?api-key=${API_KEY}&page=${page}`;
const response = await fetch(url);
const data = await response.json();
setLatestNews(data.response.docs);
setPage(page + 1);
}
我的无限滚动组件看起来像这样
<InfiniteScroll dataLength={latestNews.length} next={() => getLatestNews(page)} hasMore={true} loader={<h4>Loading...</h4>} scrollableTarget="scrollableDiv">
{
latestNews.map((article, index) => (
<div className="latest-news-article flex flex-col gap-3 mb-4" key={index}>
<p className="latest-news-article-date">
{article.pub_date.slice(11, 16)}
</p>
<h1>
{article.headline.main}
</h1>
</div>
))
}
</InfiniteScroll>
我想我现在找到了解决方案。
用我的话来说,滚动“太快了”,它更新 state 很快,比 API 可以接受请求快得多,我得到429 Too Many Requests
。 解决方案:
const getLatestNews = async () => {
setTimeout(async () => {
const response = await fetch(`https://api.nytimes.com/svc/search/v2/articlesearch.json?api-key=${API_KEY}&page=${page}`);
const data = await response.json();
setLatestNews((prev) => [...prev, ...data.response.docs]);
setPage(page + 1);
}, 5000);
}
我将 setTimeout 添加到 5000ms,这样 API 请求不会立即发送,而 state 变化就好了。 它还会相应地呈现新消息。
您的解决方案有效,但还有另一种更合乎逻辑的解决方案。
您可以使用 useRef 添加 ref 并在发送请求时更改其值,以防止同时发送另一个请求:
const sendRequestRef = useRef(true);
const getLatestNews = async () => {
if(sendRequestRef.current === true) {
sendRequestRef.current = false;
const response = await fetch(`https://api.nytimes.com/svc/search/v2/articlesearch.json?api-key=${API_KEY}&page=${page}`);
const data = await response.json();
setLatestNews((prev) => [...prev, ...data.response.docs]);
setPage(page + 1);
sendRequestRef.current = true;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.