Gatsby+MDX分页博客分页页点击文章路径多出页码前缀无法访问
问题根因
你的跳转路径用的是相对路径,没有以/开头,浏览器会默认将相对路径拼接在当前页面的URL前缀之后:
- 首页路径是
/时,相对路径slug拼接后就是/slug,符合预期 - 分页页路径是
/2时,相对路径slug拼接后就是/2/slug,就是你遇到的错误情况
解决方案
以下两种方案任选其一即可:
方案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 }, }) })
- 在列表模板给
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
相关产品推荐
相关产品推荐

