我尝试在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;
1条答案
按热度按时间7gcisfzg1#
我找到了我的问题的解决方案。Firestore没有适当的查询来向后分页,但不知何故,我设法通过玩弄查询来实现这一点。只需要修改fetchPrev函数如下所示
我们只需要运行不同的方法,这取决于页面的数量,如上面的代码所示。