firebase 在React JS中使用firestore进行分页期间,无法正确获取以前的数据

7d7tgy0s  于 2022-11-17  发布在  React
关注(0)|答案(1)|浏览(135)

我尝试在React JS中使用Firestore实现分页。我可以通过单击Next按钮获得下一组数据,但假设我在第3页,当我单击Prev按钮时,我将获得第1页的数据。因此,我没有得到确切的数据页2点击上一页按钮从第3页。当我点击第2页上的“上一页”按钮时,我从第2页到第1页获得了上一页的数据。由于没有增加页面,我没有为相应的页码获得相同的数据。下面是我的代码,你能让我知道哪里出了问题吗?
First.js

import {
  collection,
  endAt,
  getDocs,
  limit,
  orderBy,
  query,
  startAfter,
  startAt,
} from "firebase/firestore";
import React, { useState, useEffect } from "react";
import { useSelector } from "react-redux";
import BlogSection from "../component/BlogSection";
import Pagination from "../component/Pagination";
import { db } from "../firebase";

const Blogs = () => {
  const { blogs } = useSelector((state) => state.app);
  const [data, setData] = useState([]);
  const [currentPage, setCurrentPage] = useState(1);
  const [lastVisible, setLastVisible] = useState([]);
  const [prev, setPrev] = useState(false);
  const noOfPages = Math.ceil(blogs.length / itemPerPage);

  const getBlogsData = async () => {
    const blogRef = collection(db, "blogs");
    const first = query(blogRef, orderBy("title"), limit(4));
    const docSnapshot = await getDocs(first);
    setData(docSnapshot.docs.map((doc) => ({ id: doc.id, ...doc.data() })));
    setLastVisible(docSnapshot.docs[docSnapshot.docs.length - 1]);
  };

  const fetchMore = async () => {
    const blogRef = collection(db, "blogs");
    const queryMoreBlogs = query(
      blogRef,
      orderBy("title"),
      startAfter(lastVisible),
      limit(4)
    );
    const moreBlogs = await getDocs(queryMoreBlogs);
    setData(moreBlogs.docs.map((doc) => ({ id: doc.id, ...doc.data() })));
    setLastVisible(moreBlogs.docs[moreBlogs.docs.length - 1]);
  };

  const fetchPrev = async () => {
    const blogRef = collection(db, "blogs");
    const queryPrevBlogs = query(
      blogRef,
      orderBy("title"),
      endAt(lastVisible),
      limit(4)
    );
    const prevBlogs = await getDocs(queryPrevBlogs);
    setData(prevBlogs.docs.map((doc) => ({ id: doc.id, ...doc.data() })));
    setLastVisible(prevBlogs.docs[prevBlogs.docs.length - 1]);
  };

  console.log("lastVisible", lastVisible);

  const handlePageChange = (value) => {
    console.log("value", value);
    if (value === "Next") {
      setCurrentPage((next) => next + 1);
      fetchMore();
    } else if (value === "Prev") {
      setCurrentPage((prev) => prev - 1);
      fetchPrev();
    }
  };

  console.log("currentPage", currentPage);
  useEffect(() => {
    getBlogsData();
  }, []);

  return (
    <div>
      <div className="container">
        <div className="row">
          <div className="blog-heading text-center py-2 mb-4">Blogs</div>
          {data?.map((item) => (
            <div className="col-md-6">
              <BlogSection {...item} />
            </div>
          ))}
        </div>
        <Pagination
          currentPage={currentPage}
          handlePageChange={handlePageChange}
        />
      </div>
    </div>
  );
};

export default Blogs;
7gcisfzg

7gcisfzg1#

我找到了我的问题的解决方案。Firestore没有适当的查询来向后分页,但不知何故,我设法通过玩弄查询来实现这一点。只需要修改fetchPrev函数如下所示

const fetchPrev = async () => {
    const blogRef = collection(db, "blogs");
    const end =
      noOfPages !== currentPage ? endAt(lastVisible) : endBefore(lastVisible);
    const limitData = noOfPages !== currentPage ? limit(4) : limitToLast(4);
    const queryPrevBlogs = query(blogRef, orderBy("title"), end, limitData);
    const prevBlogs = await getDocs(queryPrevBlogs);
    setData(prevBlogs.docs.map((doc) => ({ id: doc.id, ...doc.data() })));
    setLastVisible(prevBlogs.docs[prevBlogs.docs.length - 1]);
  };

我们只需要运行不同的方法,这取决于页面的数量,如上面的代码所示。

相关问题