Gatsby+MDX搭建分页博客首页点击上一页跳转404错误求助
问题根因
- 你的分页路径生成规则没有创建
/blog/1路径:第一页路径为/blog,第二页开始为/blog/2、/blog/3以此类推,/blog/1本身就是不存在的路径,任何跳转到此路径的请求都会触发404。 - 原有分页跳转逻辑未适配路径规则:当
currentPage为2时,按原有逻辑会计算出prevPage = /blog/1,直接触发404;如果第一页出现跳转异常,大概率是currentPage类型不匹配(数字1和字符串"1"用===判断不相等,导致逻辑走了else分支)。
解决方案
分两种可选方案:
方案一:统一分页路径规则(更推荐,长期维护成本更低)
修改gatsby-node.js的路径生成逻辑,补齐/blog/1路径,同时保留/blog路径作为入口:
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 postEdges = data.allMdx.edges const numPages = Math.ceil(postEdges.length / postPerPage) // 生成所有数字格式的分页路径 /blog/1、/blog/2 ... /blog/n Array.from({ length: numPages }).forEach((_, i) => { const currentPage = i + 1 actions.createPage({ path: `/blog/${currentPage}`, component: require.resolve("./src/templates/allPosts.js"), context: { limit: postPerPage, skip: i * postPerPage, numPages, currentPage, }, }) }) // 额外生成 /blog 路径指向第一页内容 actions.createPage({ path: `/blog`, component: require.resolve("./src/templates/allPosts.js"), context: { limit: postPerPage, skip: 0, numPages, currentPage: 1, }, }) }
修改后原有跳转逻辑不需要调整即可正常运行,所有分页路径都真实存在。
方案二:仅修改跳转逻辑适配现有路径
如果不想调整路径生成规则,直接修改模板中的分页路径计算逻辑,避开不存在的/blog/1路径:
// allPosts模板中修改prevPage、nextPage计算逻辑 const current = Number(currentPage) // 先转数字避免类型不匹配导致判断失效 const prevPage = current <= 2 ? `/blog` : `/blog/${current - 1}` const nextPage = current === numPages ? (numPages === 1 ? `/blog` : `/blog/${current}`) : `/blog/${current + 1}`
优化建议
建议给分页按钮加边界禁用逻辑,避免用户点击无效的上一页/下一页:
修改Pagination组件代码:
import { Link } from "gatsby" import React from "react" const Pagination = ({ prevPage, nextPage, currentPage, numPages }) => { const current = Number(currentPage) const isFirstPage = current === 1 const isLastPage = current === Number(numPages) return ( <div className="flex justify-center"> {!isFirstPage && ( <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" > 上一页 </Link> )} {!isLastPage && ( <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" > 下一页 </Link> )} </div> ) } export default Pagination
同时修改模板中调用Pagination的代码,传入必要参数:
<Pagination prevPage={prevPage} nextPage={nextPage} currentPage={currentPage} numPages={numPages} />
如果修改后仍然出现异常,先执行gatsby clean清除本地构建缓存,再重启开发服务即可。
内容的提问来源于stack exchange,提问作者lucior
相关产品推荐
相关产品推荐

