简体   繁体   English

React - Cloud FireStore - 如何向该组件添加分页?

[英]React - Cloud FireStore - How can I add pagination to this component?

I'm trying to add a simple pagination for this React component.我正在尝试为这个 React 组件添加一个简单的分页。

First I run a query to find out the total number of documents in the collection.首先,我运行一个查询来找出集合中的文档总数。 Next, inside useEffect, I run a second query to show the data.接下来,在 useEffect 中,我运行第二个查询来显示数据。 Ideally it should show 10 documents on each page.理想情况下,它应该在每页上显示 10 个文档。

import React, { useState, useEffect } from 'react';
import { db } from '../firebase';
import UpdateCard from './UpdateCard';

const List = () => {
  const [cards, setCards] = useState([]);
  const [beginAfter, setBeginAfter] = useState(0);
  const [totalDoclNumbers, setTotalDoclNumbers] = useState(0);

  const docLimit = 10;

  const firstFetch = async () => {
    const data = await db
      .collection('FlashCards')
      .get();
    setTotalDoclNumbers(data.docs.length);
    console.log('totalDoclNumbers is: ' + totalDoclNumbers);
  };

  firstFetch();

  useEffect(() => {
    const fetchData = async () => {
      const data = await db
        .collection('FlashCards')
        .orderBy('customId', 'asc')
        .limit(docLimit)
        .startAfter(beginAfter)
        .get();
      setCards(data.docs.map((doc) => ({ ...doc.data(), id: doc.id })));

    };
    fetchData();
  }, [beginAfter]);

  // Creating a menu for our documents (100 documents per each menu)
  const RenderDocumentMenu = () =>
    Array(totalDoclNumbers / docLimit)
      .fill()
      .map((_, i) => {
        const onClick = () => setBeginAfter(docLimit * i);
        return (
          <div key={i} className='document__set' onClick={onClick}>
            {docLimit * i + 1} to {docLimit * i + docLimit} Data
          </div>
        );
      });

  return (
    <>
      <div className='document'>
        <RenderDocumentMenu />
      </div>

      <ul className='list'>
        {cards.map((card) => (
          <li key={card.id} className='list__item'>
            <UpdateCard card={card} />
            <DeleteCard card={card} />
          </li>
        ))}
      </ul>
      <AddCard />
    </>
  );
};

export default List;

But when I run the code I get this error: RangeError: Invalid array length On the following line: const RenderDocumentMenu = () =>但是当我运行代码时,我得到了这个错误: RangeError: Invalid array length On the following line: const RenderDocumentMenu = () =>

OMG,.我的天啊,。 I found the problem and could fix it.我发现了问题并且可以解决它。 It turned out that the number of documents in the collection was 58 .原来,集合中的文档数量为58

totalDoclNumbers is 58 totalDoclNumbers是 58

docLimit is 10文档限制为 10

Hence the result of: Array(totalDoclNumbers / docLimit) is 5.8因此结果: Array(totalDoclNumbers / docLimit) 是5.8

And JS didn't know what to do with 5.8.并且 JS 不知道如何处理 5.8。 As it should be the number of links that it has to generate for pagination.因为它应该是它必须为分页生成的链接数。

The solution was rounding up the number (to 6 in this case):解决方案是将数字四舍五入(在本例中为 6):

Array(Math.ceil(totalDoclNumbers / docLimit))

I could use Math.round, but then if we had only let's say 54 documents in our collection, which would be rounded up to only 5 links, our solution would have ignored the last 4 documents.我可以使用 Math.round,但是如果我们只有 54 个文档在我们的集合中,这将被四舍五入到只有 5 个链接,我们的解决方案将忽略最后 4 个文档。

Therefor to cover those cases, I'm using Math.ceil to round our number upward to its nearest integer.因此,为了涵盖这些情况,我使用Math.ceil将我们的数字向上舍入到最接近的 integer。

Now the pagination is working, but I'm not sure if this is the best way to accomplish it.现在分页正在工作,但我不确定这是否是完成它的最佳方式。

Would appreciate any recommendation or improved solution.将不胜感激任何建议或改进的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从 Firestore 渲染数据以响应本机组件? - How Can I Render Data From Firestore To React Native Component? 如何添加事件以响应组件? - How can I add an event to react component? 如果我不使用云功能,如何测试我的 react js + firestore 项目? - How can I test my react js + firestore project if I didn't use cloud functions? 如何告诉我的React app我想在Firestore中更新哪个组件? - How can I tell my React app which component I want to update in Firestore? 如何在 Drupal 8 中添加一个反应组件,以使用分页列出节点 - How to add a react component in Drupal 8 for node listing with pagination 我们如何在 React 表格​​分页组件中添加文本? - How do we add a text in React table pagination component? 如何在 React 的类组件中向事件侦听器添加样式? - How can I add styling to an event listener in an class component in React? 如何向作为变量传递的react组件添加属性? - How can I add properties to a react component passed as a variable? 如何将 React web 组件动态添加到父组件? - How can I add React web components to a parent component dynamically? 如何使用 jquery 向 DOM 添加反应组件? - How can I add a react Component To the DOM with jquery?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM