【发布时间】:2021-12-18 23:26:16
【问题描述】:
我无法理解与我的用例相匹配的动态 URL 路由,示例仅展示以下结构:domain.com/categories/category1、domain.com/posts/post-1。 正如标题所说,我希望在我的博客上使用 Next.js 具有以下 URL 结构:
...
我也想要这些页面:
可访问。
感谢您的帮助
【问题讨论】:
-
“我遇到 404 错误” - 哪些页面是 404?
我无法理解与我的用例相匹配的动态 URL 路由,示例仅展示以下结构:domain.com/categories/category1、domain.com/posts/post-1。 正如标题所说,我希望在我的博客上使用 Next.js 具有以下 URL 结构:
...
我也想要这些页面:
可访问。
感谢您的帮助
【问题讨论】:
如果这对其他人有用,我已经找到了解决方案。
文件夹结构必须是这样的:
pages
[category]
[slug.tsx] // (post page)
index.tsx // (category page)
在 [slug.tsx] 页面中,您的静态路径必须反映结构:
export const getStaticPaths: GetStaticPaths = async () => {
const allPosts = await getAllPostsWithSlug();
return {
paths: allPosts?.map((post) => `/${post.category.slug}/${post.slug}`) || [],
fallback: true,
};
};
在 index.tsx(类别)页面中,同样:
export const getStaticPaths: GetStaticPaths = async () => {
const allCategories = await getAllCategories();
return {
paths: allCategories.map((category) => `/${category.slug}`) || [],
fallback: true,
};
};
有了这个,我可以在 url 中使用他们的类别访问我的帖子。
【讨论】: