【问题标题】:What is the correct folder structure for dynamic nested routes in Next.js?Next.js 中动态嵌套路由的正确文件夹结构是什么?
【发布时间】:2020-11-05 04:15:12
【问题描述】:

我一直在阅读 Next.js 文档,并认为我了解 [slug].js 动态路由过程,但我很难理解文件夹结构方面的嵌套动态路由。

如果我想做一个基于用户的应用程序,我将如何实现/user/[userid]/post/[postId]

并且a想要这样的东西:

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

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

谁能解释正确的文件夹结构来实现这一点?非常感谢任何帮助。

【问题讨论】:

    标签: javascript directory next.js


    【解决方案1】:

    [userId] 文件夹中创建一个名为index.js 的文件,而不是[id].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/,可用于显示该用户的帖子列表。

    example 具有类似用例的文件夹结构。

    【讨论】:

    • 谢谢!完美运行。
    猜你喜欢
    • 2023-03-09
    • 1970-01-01
    • 2021-01-29
    • 2021-05-05
    • 1970-01-01
    • 1970-01-01
    • 2021-12-02
    • 1970-01-01
    • 2022-07-29
    相关资源
    最近更新 更多