我正在开发一个React无限滚动组件,它的工作原理完美而完美,只有一个小问题是,对于第1页,它发出了两倍的API请求,而我不希望这样做;对于其他第2、3、4页它仅发出一次请求。
我尝试了所有操作,但无法修改代码,因此对于第1页,它仅发出一次请求。
我也只能一次发出第1页的请求吗?这是工作代码。
import React, { useState, useEffect } from "react";
import axios from "axios";
function Lists() {
const [posts, setPosts] = useState([]);
const [newposts, setNewposts] = useState([]);
const [isFetching, setIsFetching] = useState(false);
const [page, setPage] = useState(1);
const LIMIT = 7;
const getPosts = () => {
axios.get(`https://jsonplaceholder.typicode.com/posts?_limit=${LIMIT}&_page=${page}`)
.then(res => {
setNewposts(res.data);
setPosts([...posts, ...res.data]);
setIsFetching(false);
})
};
const getMorePosts= () => {
setPage(page + 1);
getPosts();
}
const handleScroll = () => {
if (
window.innerHeight + document.documentElement.scrollTop !==
document.documentElement.offsetHeight
) return;
setIsFetching(true);
}
useEffect(() => {
window.addEventListener("scroll", handleScroll);
return () => window.removeEventListener("scroll", handleScroll);
}, []);
useEffect(() => {
getPosts();
},[]);
useEffect(() => {
if (!isFetching){
return;
}
if( newposts.length > 0 ){
getMorePosts();
}
}, [isFetching]);
return (
<div className="App">
{posts.map((post, index) => (
<div key={index} className="post">
<div className="number">{post.id}</div>
<div className="post-info">
<h2 className="post-title">{post.title}</h2>
<p className="post-body">{post.body}</p>
</div>
</div>
))}
{isFetching && newposts.length > 0 && (
<div style = {{display: "flex", justifyContent:"center"}}>
<div className="spinner-border" role="status">
<span className="sr-only">Loading...</span>
</div>
</div>
)}
</div>
);
}
export default Lists;
问题是setPage
,就像任何状态设置程序一样,它是异步工作的-它不会page
立即更新您可能期望的值。的值page
将仅在状态更改触发的后续渲染中更新。
这意味着在getMorePosts()
你并没有得到真正的page + 1
收获page
。
在第一次这意味着使你打电话getPosts()
的,其他useEffect
,与page
设置为1
,然后再调用它,当你滚动和呼叫getPosts()
内部getMorePosts()
通话。
后续调用仅发生一次,因为每个后续渲染中的getMorePosts()
增量page
。
至于修复,一个快速的方法可能只是page
作为一个arg getPosts
,然后您可以静态地getPosts(1)
在第一个render上调用,并使其余逻辑保持不变,但将page
状态初始化为,2
并将调用更改为getPage(page)
inside getMorePosts()
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句