在 Next.js 中,动态嵌套路由的正确文件夹结构是什么?

12

我一直在查阅Next.js文档,认为我理解了[slug].js的动态路由过程,但是我在文件夹结构方面理解嵌套动态路由。如果我想要创建一个基于用户的应用程序,我该如何实现/user/[userid]/post/[postId]

我希望有像这样的东西:

 user
 - [id].js // e.g. user/1
 - [userId]
 - - post
 - - - [postId].js // e.g. user/[userId]/post/[postId]

但是这会出现关于[slugs]的错误,因为我认为您不能在同一文件夹中拥有两个相同的slugs。

有人能解释一下如何实现正确的文件夹结构吗?非常感谢任何帮助。

1个回答

30

不要创建[id].js,而是在[userId]文件夹中创建一个名为index.js的文件,该文件将用于渲染路由路径/user/[userId]/的页面。

pages/
 user/
  [userId]/
    - index.js        // will match for /user/1234
    post/
      - index.js      // will match for /user/1234/post
      - [postId].js   // will match for /user/1234/post/some-post
类似地,在post文件夹下创建一个index.js将有助于匹配路由路径/user/[userId]/post/,这可以用来显示该用户的帖子列表。 具有类似用例的文件夹结构的示例。 例子

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接