You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Gatsby+MDX分页博客分页页点击文章路径多出页码前缀无法访问

问题根因

你的跳转路径用的是相对路径,没有以/开头,浏览器会默认将相对路径拼接在当前页面的URL前缀之后:

  • 首页路径是/时,相对路径slug拼接后就是/slug,符合预期
  • 分页页路径是/2时,相对路径slug拼接后就是/2/slug,就是你遇到的错误情况

解决方案

以下两种方案任选其一即可:

方案1:全链路统一使用绝对路径

  1. 修改gatsby-node.js里的文章创建逻辑,路径前加/:
data.allMdx.edges.forEach(edge => {
  const slug = edge.node.frontmatter.slug
  const id = edge.node.id
  actions.createPage({
    path: `/${slug}`, // 新增前缀/
    component: require.resolve(`./src/templates/singlePost.js`),
    context: { id },
  })
})
  1. 在列表模板给ContentCard传参时也补全前缀:
<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}`} // 新增前缀/
/>

方案2:跳转组件统一做兼容处理

无需修改其他逻辑,直接在Button组件内补全绝对路径,同时兼容本身已经带/的slug场景:

export const Button = ({ children, href }) => {
  const finalHref = href.startsWith('/') ? href : `/${href}`
  return <ButtonWrapper to={finalHref}>{children}</ButtonWrapper>
}

内容的提问来源于stack exchange,提问作者lucior

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 20:24:03