如何使用Next.js中的动态路线路由到页面

发布于 2025-01-28 17:53:05 字数 331 浏览 2 评论 0原文

我试图将这些URL路由到[id] .js file。想。是否可以使用相同的[ID] .JS文件?对于URL 1。

url 1 -> /settings
url 2 -> /settings/notifications
url 3 -> /settings/security

我的文件结构

settings > [id].js

获取ID

const router = useRouter()
const { id } = router.query;

I am trying to route these urls to [id].js file in next.js, So everything is working for url 2 and 3 below, but its not working for url 1 so I have to create another index.js file which I dont want. Is is possible to use the same [id].js file? for url 1 also.

url 1 -> /settings
url 2 -> /settings/notifications
url 3 -> /settings/security

my file structure

settings > [id].js

getting the id

const router = useRouter()
const { id } = router.query;

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

一身骄傲 2025-02-04 17:53:05

下面的文件结构是一种方法:

settings 
    > [id]
    > index

但是,如果您不想添加索引文件,则可以使用可选的 catch-all路线功能。请注意,它附带了您可能不想要的其他功能,这也可能会更改您的代码。

这是您必须遵循的结构:

settings
    >[[...id]]
{ } // GET `/post` (empty object)
{ "slug": ["notifications"] } // `GET /settings/notifications ` (single-element array)
{ "slug": ["notifications", "security"] } // `GET /settings/notifications/security ` (multi-element array)

A file structure like the below is one way to do it:

settings 
    > [id]
    > index

But if you do not want to add an index file you can make use of optional catch-all routes feature. Please note that it comes with other features you might not want and this might change your code a little too.

This is the structure you will have to follow:

settings
    >[[...id]]
{ } // GET `/post` (empty object)
{ "slug": ["notifications"] } // `GET /settings/notifications ` (single-element array)
{ "slug": ["notifications", "security"] } // `GET /settings/notifications/security ` (multi-element array)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文