我正在尝试使用react- infinite - scroll -component创建一个无限滚动的firestore文档列表。为了测试,我将限制设置为5。无限滚动正在运行,但它只显示5个列表的给定限制:
目前我创建了25个不同的列表,我将firestore限制为一次显示5个:
list 1
list 2
list 3
list 4
list 5
loading more...加载后,它将加载相同的5列表,并且不加载新的列表,并且还会使用给定的5限制在无限循环中加载:
list 1
list 2
list 3
list 4
list 5
list 1
list 2
list 3
list 4
list 5
loading more...下面是获取查询的示例代码,我将其放在useEffect中,因为它位于用户页面和主页中的上下文提供者包装中,两者都使用无限滚动:
import InfiniteScroll from 'react-infinite-scroll-component';
const [list, setList] = useState([]);
const [last, setLast] = useState(null);
useEffect(() => {
firestoreList
.orderBy('createdAt', "desc")
.limit(5)
.get()
.then((querySnapshot) => {
const lastVisible = querySnapshot.docs[querySnapshot.docs.length - 1];
setLast(lastVisible.data());
const postList = []
querySnapshot.forEach((doc) => {
postList.push(doc.data());
})
setList(postList);
})
.catch((err) => {
console.log(err)
})
},[]};以下是获取数据的代码:
const {list, last, setList } = ListContext();
const fetchMoreData = () => {
firestoreList
.orderBy('createdAt', "desc")
.startAfter(last)
.limit(5)
.get()
.then(() => {
setList(list.concat(list));
})
.catch((err) => {
console.log(err)
})
};而对于react-infinite-scroll-component:
<InfiniteScroll
dataLength={list.length}
next={fetchMoreData}
hasMore={true}
>
{list.map((a, i) => (
<div key={i}>
{a.allList}
<div>
))}
<InfiniteScroll>如何正确设置限制并使其他列表出现并停止循环?
发布于 2020-10-08 21:17:16
我现在终于让它工作了,我在这个youtube通道上得到了灵感,我还应该在我的fetchMoreData中定义一个lastVisible,并停止给出一个错误为undefined的循环。
const {list, last, setList, setLast } = ListContext();
const [notify, setNotify] = useState(null);
const fetchMoreData = () => {
const field = "createdAt";
firestoreList
.orderBy(field, "desc")
.startAfter(last[field]) //from Fireship channel, which loads the next data
.limit(5)
.get()
.then((querySnapshot) => {
const lastVisible = querySnapshot.docs[querySnapshot.docs.length - 1];
const postList = []
querySnapshot.forEach((doc) => {
postList.push(doc.data());
})
if (lastVisible !== undefined) {
setList([...list, ...postList]);
setLast(lastVisible.data());
} else {
setNotify("nothing to load.");
return;
}
})
.catch((err) => {
console.log(err)
})
};即使不使用“react-infinite scroll-component”,只要使用useEffect,它也可以正常工作。
https://stackoverflow.com/questions/64169968
复制相似问题