Skip to main content

定义路由

我们建议你先阅读 路由基础知识 页,然后再继续。

¥We recommend reading the Routing Fundamentals page before continuing.

本页面将指导你如何在 Next.js 应用中定义和组织路由。

¥This page will guide you through how to define and organize routes in your Next.js application.

创建路由

¥Creating Routes

Next.js 使用基于文件系统的路由,其中使用文件夹来定义路由。

¥Next.js uses a file-system based router where folders are used to define routes.

每个文件夹代表一个映射到 URL 段的 路由片段。要创建 嵌套路由,你可以将文件夹相互嵌套。

¥Each folder represents a route segment that maps to a URL segment. To create a nested route, you can nest folders inside each other.

特殊的 page.js file 用于使路由段可公开访问。

¥A special page.js file is used to make route segments publicly accessible.

在此示例中,/dashboard/analytics URL 路径不可公开访问,因为它没有相应的 page.js 文件。该文件夹可用于存储组件、样式表、图片或其他并置文件。

¥In this example, the /dashboard/analytics URL path is not publicly accessible because it does not have a corresponding page.js file. This folder could be used to store components, stylesheets, images, or other colocated files.

很高兴知道:.js.jsx.tsx 文件扩展名可用于特殊文件。

¥Good to know: .js, .jsx, or .tsx file extensions can be used for special files.

创建用户界面

¥Creating UI

特殊文件约定 用于为每个路由段创建 UI。最常见的是 pages 显示路由独有的 UI,layouts 显示跨多个路由共享的 UI。

¥Special file conventions are used to create UI for each route segment. The most common are pages to show UI unique to a route, and layouts to show UI that is shared across multiple routes.

例如,要创建第一个页面,请在 app 目录中添加 page.js 文件并导出 React 组件:

¥For example, to create your first page, add a page.js file inside the app directory and export a React component:

export default function Page() {
return <h1>Hello, Next.js!</h1>
}
export default function Page() {
return <h1>Hello, Next.js!</h1>
}