2级别的动态路由在Next.js中

huangapple go评论46阅读模式
英文:

2 Level of dynamic routing in next.js

问题

我是新手,想问一下如何在next.js中实现两级动态路由?

我的URL是http://localhost:3000/company/[slug1]/[slug2]。

在next.js的官方文档中,我只找到了一级嵌套路由。

我想要两级路由。

请帮助我。

英文:

I am new to next.js. I want to ask how to achieve two level of dynamic routing in next.js?

My url is http://localhost:3000/company/[slug1]/[slug2]

In the next.js's official documentation I got only one level nesting routing.

I want to 2 level routing.

Plese help me.

答案1

得分: 1

创建类似以下的目录结构

pages/
 └─ company/
     └─ [slug1]/
         └─ [slug2].js

要在客户端访问片段

import { useRouter } from 'next/router';

export function Component() {
  const router = useRouter();
  const { slug1, slug2 } = router.query;
  // ...
}

或者如果在服务器端

export async function getServerSideProps(ctx) {
  const { slug1, slug2 } = ctx.params;
  // ...
}
英文:

Create directory structure like this

pages/
 └─ company/
     └─ [slug1]/
         └─ [slug2].js

To access segments on the client side

import { useRouter } from 'next/router';

export function Component() {
  const router = useRouter();
  const { slug1, slug2 } = router.query;
  // ...
}

Or if on the server side

export async function getServerSideProps(ctx) {
  const { slug1, slug2 } = ctx.params;
  // ...
}

huangapple
  • 本文由 发表于 2023年5月22日 17:06:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/76304562.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定