如何使用 ReactJs 对 Cloud Firestore 数据进行分页 [英] How to paginate Cloud Firestore data with ReactJs

查看:23
本文介绍了如何使用 ReactJs 对 Cloud Firestore 数据进行分页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Firebase - Cloud Firestore,目前我想对所有可用记录进行分页.我已经有了一个记录列表,剩下的是一些分页.我是 Cloud Firestore 的新成员,因此感谢您提供清晰的信息.

我查看了 Firestore 文档(https://firebase.google.com/docs/firestore/query-data/query-cursors#paginate_a_query) 和 ReactJS 示例,但可用的不多.

我理解例如:.startAt(0), .limit(10),但问题是如何使用在渲染方法中调用的这个组件正确分页.

import React, { Component } from 'react';从react-js-pagination"导入分页;从./Firebase"导入 firestore;导出默认类 DataList 扩展组件 {构造函数(道具){超级(道具);this.state = {dbItems: [],当前页面:1,每页项目数:3,totalItemCount: 1,活动页面:15}this.handlePageChange = this.handlePageChange.bind(this);}handlePageChange(pageNumber) {console.log(`活动页面是 ${pageNumber}`);this.setState({ activePage: pageNumber });}异步 getItems() {const { currentPage, itemsPerPage } = this.state;const startAt = currentPage * itemsPerPage - itemsPerPage;const usersQuery = firestore.collection('Users').orderBy("email").startAt(startAt).limit(itemsPerPage)const 快照 = 等待 usersQuery.get()const items = snapshot.docs.map(doc => doc.data())返回 this.setState({dbItems:项目,totalItemCount: firestore.collection('Users').get().then(res => console.log(res.size))})}componentDidMount() {this.getItems()}componentDidUpdate(prevProps, prevState) {const isDifferentPage = this.state.currentPage !== prevState.currentPageif (isDifferentPage) this.getItems()}使成为() {返回 (<div>{this.state.dbItems.map((users, index) => {返回 (<p key={index}><b>名字:</b>{users.firstname} 
<b>电子邮件:</b>{users.email}</p>)})}<分页activePage={this.state.activePage}itemsCountPerPage={this.state.itemsPerPage}totalItemsCount={this.state.totalItemCount}pageRangeDisplayed={this.state.itemsPerPage}onChange={this.handlePageChange}/>

)}}

感谢您的帮助!

解决方案

可以使用 startAt()

//获取物品.异步 fetchUsers = () =>{//状态.const {users, usersPerPage} = this.state//最后可见.const lastVisible = 用户 &&users.docs[users.docs.length - 1]//询问.const query = firestore.collection('用户').orderBy('email').startAfter(lastVisible).limit(usersPerPage)//用户.const 用户 = 等待 query.get()//..返回 this.setState({users})}//是否挂载.componentDidMount() {this.fetchUsers()}//是否更新.componentDidUpdate(prevProps, prevState) {const isDifferentPage = this.state.currentPage !== prevState.currentPageif (isDifferentPage) this.fetchUsers()}

I'm working with Firebase - Cloud Firestore and at the moment I would like to paginate all the records available. I already have a list of records and what is left is some pagination for this. I'm new with Cloud Firestore, so any clarity is appreciated.

I checked the Firestore documentation (https://firebase.google.com/docs/firestore/query-data/query-cursors#paginate_a_query) and examples with ReactJS, but there is not much available.

I understand that eg:.startAt(0), .limit(10), but the question is how to paginate properly with this component called at the render method.

import React, { Component } from 'react';
import Pagination from "react-js-pagination";
import firestore from "./Firebase";

export default class DataList extends Component {

constructor(props) {
    super(props);
    this.state = {
        dbItems: [],
        currentPage: 1,
        itemsPerPage: 3,
        totalItemCount: 1,
        activePage: 15
    }
    this.handlePageChange = this.handlePageChange.bind(this);
}

handlePageChange(pageNumber) {
    console.log(`active page is ${pageNumber}`);
    this.setState({ activePage: pageNumber });
}

async getItems() {
    const { currentPage, itemsPerPage } = this.state;
    const startAt = currentPage * itemsPerPage - itemsPerPage;
    const usersQuery = firestore.collection('Users').orderBy("email").startAt(startAt).limit(itemsPerPage)
    const snapshot = await usersQuery.get()
    const items = snapshot.docs.map(doc => doc.data())
    return this.setState({ 
        dbItems: items,
        totalItemCount: firestore.collection('Users').get().then(res => console.log(res.size))
    })

}

componentDidMount() {
    this.getItems()
}

componentDidUpdate(prevProps, prevState) {
    const isDifferentPage = this.state.currentPage !== prevState.currentPage
    if (isDifferentPage) this.getItems()
}

render() {
    return (
        <div>
            {this.state.dbItems.map((users, index) => {
                return (
                    <p key={index}>
                        <b>First Name:</b> {users.firstname} <br />
                        <b>Email:</b> {users.email}
                    </p>
                )
            })
            }
            <Pagination
                activePage={this.state.activePage}
                itemsCountPerPage={this.state.itemsPerPage}
                totalItemsCount={this.state.totalItemCount}
                pageRangeDisplayed={this.state.itemsPerPage}
                onChange={this.handlePageChange}
            />
        </div>
    )
}
}

Thank you for the help!

解决方案

Pagination can be achieved using startAt()

// Get Items.
async fetchUsers = () => {

  // State.
  const {users, usersPerPage} = this.state

  // Last Visible.
  const lastVisible = users && users.docs[users.docs.length - 1]

  // Query.
  const query = firestore.collection('Users')
    .orderBy('email')
    .startAfter(lastVisible)
    .limit(usersPerPage)

  // Users.
  const users = await query.get()

  // ..
  return this.setState({users})

}

// Did Mount.
componentDidMount() {
  this.fetchUsers()
}

// Did Update.
componentDidUpdate(prevProps, prevState) {
  const isDifferentPage = this.state.currentPage !== prevState.currentPage
  if (isDifferentPage) this.fetchUsers()
}

这篇关于如何使用 ReactJs 对 Cloud Firestore 数据进行分页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆