如何按Firestore中的项目数进行分页或无限滚动? [英] How to paginate or infinite scroll by number of items in firestore?
问题描述
要求
- 开始时将加载20个项目.
- 当用户滚动到末尾时,将再加载20个项目.
问题Firestore查询具有 startAt()
和 endAt()
方法,它们对 OrderBy
字段的值起作用.我希望对索引有所帮助.
Problem
Firestore Query has startAt()
and endAt()
methods which works on value of OrderBy
field. I want something to work on index.
interface Product{
price:number;
}
假设有20种产品的价格为20 $,而30种产品的价格为10 $.可以提取初次装载
Suppose there are 100 products for 20$ and 30 products for 10$. First load can be fetched
query
.orderBy(price,desc)
.limitTo(20)
现在最后一件商品的价格是20 $.要加载下20个结果
Now price of last item is 20$. To load next 20 results
query
.orderBy(price,desc)
.startAt(20$)
.limitTo(20)
它将返回相同的结果.
推荐答案
You should "use a document snapshot to define the query cursor" as explained in the documentation here: https://firebase.google.com/docs/firestore/query-data/query-cursors#use_a_document_snapshot_to_define_the_query_cursor
因此,您将执行以下操作:
Therefore you would do as follows:
var first = db.collection("....").orderBy("price", "desc").limit(20);
return first.get().then(function (documentSnapshots) {
// Get the last visible document
var lastVisible = documentSnapshots.docs[documentSnapshots.docs.length-1];
console.log("last", lastVisible);
// Construct a new query starting at this document,
// Get the next 20 cities.
var next = db.collection("....")
.orderBy("price", "desc")
.startAfter(lastVisible)
.limit(20);
});
这篇关于如何按Firestore中的项目数进行分页或无限滚动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!