【问题标题】:Next.js : URL with domain.com/category/postNext.js : 带有 domain.com/category/post 的 URL
【发布时间】:2021-12-18 23:26:16
【问题描述】:

我无法理解与我的用例相匹配的动态 URL 路由,示例仅展示以下结构:domain.com/categories/category1、domain.com/posts/post-1。 正如标题所说,我希望在我的博客上使用 Next.js 具有以下 URL 结构:

...

我也想要这些页面:

可访问。

到目前为止,我的文件结构如下所示: 但出现 404 错误。

感谢您的帮助

【问题讨论】:

  • “我遇到 404 错误” - 哪些页面是 404?

标签: reactjs routes next.js


【解决方案1】:

如果这对其他人有用,我已经找到了解决方案。

文件夹结构必须是这样的:

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 中使用他们的类别访问我的帖子。

【讨论】:

    猜你喜欢
    • 2014-12-10
    • 2017-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-03
    • 2019-06-27
    • 1970-01-01
    • 2021-07-12
    相关资源
    最近更新 更多