Astro博客分页报错:getStaticPaths匹配路由但未找到静态路径
问题分析与解决方案
错误原因
你错误地在每篇文章条目上单独调用paginate,这完全不符合它的使用场景:
paginate是用来将列表数据分割成多页列表页(比如/en/tasmania?page=1这类分页路径),但你的路由结构[lang]/[chapter]/[page]中,page是文章slug的一部分,和分页的page参数冲突,导致生成的路径无法匹配路由规则,触发错误。- 你要实现的是单篇文章的「上一页/下一页」导航,不需要用
paginate,只需在getStaticPaths中为每篇文章计算同语言同分类下的前后篇即可。
修正代码
1. 修改getStaticPaths逻辑
export async function getStaticPaths() { const pages = await getCollection("places"); // 按「语言+分类」分组,便于找到同组内的文章 const groupedPages = pages.reduce((groups, page) => { const [lang, chapter] = page.slug.split("/"); const key = `${lang}/${chapter}`; if (!groups[key]) groups[key] = []; groups[key].push(page); // 可按发布日期排序(根据你的需求调整排序规则) groups[key].sort((a, b) => new Date(b.data.date) - new Date(a.data.date)); return groups; }, {}); const paths = pages.map((currentPage) => { const [lang, chapter, pageSlug] = currentPage.slug.split("/"); const group = groupedPages[`${lang}/${chapter}`]; const currentIndex = group.findIndex(page => page.slug === currentPage.slug); // 获取同组内的上一篇和下一篇文章 const prevPage = currentIndex > 0 ? group[currentIndex - 1] : null; const nextPage = currentIndex < group.length - 1 ? group[currentIndex + 1] : null; return { params: { lang, chapter, page: pageSlug }, // 参数名与路由[page]对应 props: { page: currentPage, // 仅传递需要的字段(比如slug、标题),避免冗余 prevPage: prevPage ? { slug: prevPage.slug, title: prevPage.data.title } : null, nextPage: nextPage ? { slug: nextPage.slug, title: nextPage.data.title } : null } }; }); return paths; }
2. 页面组件中渲染导航
在你的文章页面组件(比如[lang]/[chapter]/[page].astro)中,通过Astro.props拿到前后页数据并渲染:
--- const { page, prevPage, nextPage } = Astro.props; --- <article> <h1>{page.data.title}</h1> <div set:html={page.content}></div> </article> <nav class="pagination"> {prevPage && ( <a href={`/${prevPage.slug}`}>← {prevPage.title}</a> )} {nextPage && ( <a href={`/${nextPage.slug}`}>{nextPage.title} →</a> )} </nav>
内容的提问来源于stack exchange,提问作者user3176609
相关产品推荐
相关产品推荐

