动态路由与全匹配片段
使用动态片段和全匹配路由创建能够适应动态内容的灵活路由。
动态路由与全匹配片段 是 CoddyKit 上的免费 Next.js 15 Fullstack Web Apps 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Next.js 15 Fullstack Web Apps 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Next.js 15 Fullstack Web Apps 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Flexible Routing in Next.js
Welcome to dynamic routing in Next.js! Modern web applications often need flexible URLs for content like blog posts, product details, or user profiles.
Instead of creating a separate page for each item, dynamic routes let you use a single page template to handle many different URLs based on their path.
Creating Dynamic Segments
In Next.js, you create a dynamic route by enclosing a folder name in square brackets, like [slug].
This [slug] segment acts as a placeholder. Whatever value is in that part of the URL will be captured and made available to your page component.
- Example:
app/blog/[slug]/page.js - This will match URLs like
/blog/hello-worldor/blog/nextjs-tips.
Accessing Dynamic Parameters
When a dynamic route is matched, the value of the dynamic segment (e.g., slug) is passed to your page component as a property of the params object.
By default, Next.js App Router pages are React Server Components, which receive params as a prop.
// File: app/blog/[slug]/page.js
export default function BlogPostPage({ params }) {
const { slug } = params; // If URL is /blog/my-post, slug will be 'my-post'
return (
<main>
<h1>Blog Post: {decodeURIComponent(slug)}</h1>
<p>This content is for the post identified by '{decodeURIComponent(slug)}'.</p>
</main>
);
}Introducing Catch-all Segments
What if you need to match URLs with an unknown number of segments? For example, a documentation site where paths can be deeply nested (e.g., /docs/getting-started/installation).
This is where catch-all segments come in. They capture all subsequent path segments into an array.
Creating Catch-all Routes
To create a catch-all route, use three dots followed by the segment name inside square brackets: [...slug].
This will match any path that starts with the parent folder and capture all parts after it into an array.
- Example:
app/docs/[...slug]/page.js - Matches:
/docs/a,/docs/a/b,/docs/a/b/c. slugwill be an array:['a'],['a', 'b'],['a', 'b', 'c'].
Accessing Catch-all Parameters
Similar to dynamic segments, catch-all parameters are available via the params object. However, the value for a catch-all segment is always an array of strings.
Let's see an example of displaying the captured path segments from a URL like /docs/guide/setup/nextjs.
// File: app/docs/[...slug]/page.js
export default function DocsPage({ params }) {
const { slug } = params; // If URL is /docs/intro/setup, slug is ['intro', 'setup']
return (
<main>
<h2>Documentation Path: /{slug.join('/')}</h2>
<p>Segments found: {slug.map(s => `<code>${s}</code>`).join(', ')}</p>
</main>
);
}Optional Catch-all Segments
What if you want a catch-all route to also match the base path? For example, you want /docs to show an index page, but /docs/intro to show a specific guide.
You can make a catch-all segment optional by wrapping it in an extra set of square brackets: [[...slug]].
- Example:
app/docs/[[...slug]]/page.js - Matches:
/docsand/docs/a/b.
Optional Catch-all Example
When using [[...slug]], the slug parameter will be an array of strings for sub-paths. However, it will be undefined if only the base path is matched (e.g., /docs).
You'll need to handle the undefined case in your component to show default content.
// File: app/docs/[[...slug]]/page.js
export default function OptionalDocsPage({ params }) {
const { slug } = params; // If URL is /docs, slug is undefined
// If URL is /docs/intro, slug is ['intro']
const pathDisplay = slug ? slug.join('/') : 'Home Index';
return (
<main>
<h2>Docs: {pathDisplay}</h2>
<p>This page handles both the base path and any sub-paths.</p>
</main>
);
}Quick Check on Routing
Which of the following statements about Next.js dynamic and catch-all routes are TRUE?
Recap: Dynamic & Catch-all Routes
You've mastered how to make your Next.js application's routing incredibly flexible!
- Dynamic Segments (
[slug]) allow a single page to handle many specific URLs, receiving a string parameter. - Catch-all Segments (
[...slug]) capture multiple path segments into an array, useful for nested structures. - Optional Catch-all Segments (
[[...slug]]) extend catch-alls to also match the base path, with the parameter beingundefinedfor the base path.
These powerful patterns are fundamental for building scalable and content-rich applications in Next.js.
常见问题解答
「动态路由与全匹配片段」课时是免费的吗?
是的 — 「动态路由与全匹配片段」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Next.js 15 Fullstack Web Apps 课程的其余内容,请升级到 CoddyKit PRO。 Next.js 15 Fullstack Web Apps 课程共包含 4 节课。
「动态路由与全匹配片段」这节课中我会学到什么?
使用动态片段和全匹配路由创建能够适应动态内容的灵活路由。 你通过在浏览器中直接运行的动手代码来练习 Next.js 15 Fullstack Web Apps,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Next.js 15 Fullstack Web Apps 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Next.js 15 Fullstack Web Apps 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。
「动态路由与全匹配片段」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Next.js 15 Fullstack Web Apps 课中编写并运行代码吗?
能。每节 Next.js 15 Fullstack Web Apps 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 动态路由与全匹配片段
- 嵌套路由布局与路由组
- 并行路由与拦截路由
- 加载与错误 UI 约定