基于pageNumber和PageIndex的Firestore分页



我正在查看Firestore文档中的分页。如果你需要下一个文档,它似乎是基于最后一个快照,按照下面的文章:

https://firebase.google.com/docs/firestore/query-data/query-cursors

但我的结束,我只得到indexNumber(pageNumber)和pageSize,如indexNumber (pageNumber)是2和页面大小是4。我如何实现这里的索引和pageSize分页?我可以将pageSize放在limit(4)中,但是我如何从索引2或页码2开始获得文档的子集呢?以下是文档中编写的代码:

import { collection, query, orderBy, startAfter, limit, getDocs } from "firebase/firestore";  
// Query the first page of docs
const first = query(collection(db, "cities"), orderBy("population"), limit(25));
const documentSnapshots = await getDocs(first);
// Get the last visible document
const lastVisible = documentSnapshots.docs[documentSnapshots.docs.length-1];
console.log("last", lastVisible);
// Construct a new query starting at this document,
// get the next 25 cities.
const next = query(collection(db, "cities"),
orderBy("population"),
startAfter(lastVisible),
limit(25));

我看不出你为什么要实现这样的分页,因为现在我们正在使用所谓的无限滚动。的确,您可以计算集合中的文档数,并将其除以每页的文档数,这样您就可以得到页面数,但是这样做值得吗?

很可能不会,因为它要求您事先阅读所有文档,这听起来有点昂贵。Firestore没有支持基于索引或偏移量的分页。正如官方文档所述,分页要求您提供一个DocumentReference,它表示下一个查询的起点。这基本上意味着您的分页将从查询的开头开始,然后您可以使用在页面(屏幕)上看到的最后一个文档加载其他结果。

上面的解决方案可以很容易地实现,并且与传统方法相比,它的成本要低得多,因为您总是将数据逐步加载到更小的块中。

最新更新