【发布时间】:2021-12-31 23:43:35
【问题描述】:
我正在尝试使用 gatsby 和 MDX 构建一个分页博客,当我在我的博客的第一页上使用 URL /blog 并且我按下上一页按钮时验证不起作用,而不是停留在第一页它转到不存在的 /blog/1 并引发 404 错误。这是我的模板,我尝试检查我的 currentPage 是否为 1 我需要返回博客,否则它需要返回 /blog/${currentPage - 1}(这是有效的)。我也尝试验证 currentPage - 1 === 1 但出现相同的错误。
import React from "react"
import { graphql } from "gatsby"
import BlogHomepage from "../components/BlogHomepage"
import Layout from "../components/Layout"
import Pagination from "../components/Pagination"
import ContentCard from "../components/ContentCard"
const allPosts = ({ pageContext, data }) => {
const { currentPage, numPages } = pageContext
const prevPage = currentPage === 1 ? `/blog` : `/blog/${currentPage - 1}`
const nextPage =
currentPage === numPages
? `/blog/${currentPage}`
: `/blog/${currentPage + 1}`
const posts = data.allMdx.edges
return (
<Layout>
<BlogHomepage>
{posts.map(post => {
return (
<ContentCard
key={post.node.frontmatter.slug}
date={post.node.frontmatter.date}
title={post.node.frontmatter.title}
excerpt={post.node.frontmatter.excerpt}
slug={post.node.frontmatter.slug}
/>
)
})}
<Pagination prevPage={prevPage} nextPage={nextPage} />
</BlogHomepage>
</Layout>
)
}
export default allPosts
export const pageQuery = graphql`
query AllPostsQuery($skip: Int!, $limit: Int!) {
allMdx(
sort: { fields: frontmatter___date, order: DESC }
skip: $skip
limit: $limit
) {
edges {
node {
frontmatter {
slug
title
date
excerpt
}
}
}
}
}
另外,我只是将 prevPage 和 nextPage 作为 props 传递的分页按钮组件
import { Link } from "gatsby"
import React from "react"
const Pagination = ({ prevPage, nextPage }) => {
return (
<div className="flex justify-center">
<Link
to={prevPage}
className="inline-flex text-white bg-blue-500 border-0 py-2 px-6 focus:outline-none hover:bg-blue-600 rounded text-lg"
>
Prev
</Link>
<Link
to={nextPage}
className="ml-4 inline-flex text-gray-400 bg-gray-800 border-0 py-2 px-6 focus:outline-none hover:bg-gray-700 hover:text-white rounded text-lg"
>
Next
</Link>
</div>
)
}
export default Pagination
在 gatsby-node 内部,我将 currentPage 定义为数组 pages + 1 的索引
exports.createPages = async function ({ actions, graphql }) {
const { data } = await graphql(`
query {
allMdx(sort: { fields: frontmatter___date, order: DESC }) {
edges {
node {
frontmatter {
slug
}
id
}
}
}
}
`)
const postPerPage = 3
const numPages = Math.ceil(data.allMdx.edges.length / postPerPage)
Array.from({ length: numPages }).forEach((_, i) => {
actions.createPage({
path: i === 0 ? `/blog` : `/blog/${i + 1}`,
component: require.resolve("./src/templates/allPosts.js"),
context: {
limit: postPerPage,
skip: i * postPerPage,
numPages,
currentPage: i + 1,
},
})
})
}
分页的其余部分正在工作。
【问题讨论】:
标签: javascript reactjs pagination graphql