路由基礎
每個應用程式的骨架都是路由。本頁將介紹網頁路由的基本概念,以及如何在 Next.js 中處理路由。
術語
首先,您會在整個文件中看到這些術語。以下是快速參考


- 樹狀結構 (Tree): 一種用於視覺化階層結構的慣例。例如,具有父元件和子元件的元件樹、資料夾結構等等。
- 子樹 (Subtree): 樹狀結構的一部分,從新的根節點(第一個)開始,到葉節點(最後一個)結束。
- 根節點 (Root): 樹狀結構或子樹中的第一個節點,例如根佈局。
- 葉節點 (Leaf): 子樹中沒有子節點的節點,例如 URL 路徑中的最後一個區段。


- URL 區段 (URL Segment): URL 路徑中由斜線分隔的部分。
- URL 路徑 (URL Path): 網域名稱之後的 URL 部分(由區段組成)。
app
路由器
在版本 13 中,Next.js 引入了一個新的基於 React 伺服器元件 構建的應用程式路由器 (App Router),它支援共用佈局、巢狀路由、載入狀態、錯誤處理等等。
應用程式路由器在名為 app
的新目錄中運作。app
目錄與 pages
目錄一起運作,允許漸進式採用。這允許您將應用程式中的某些路由選擇加入新的行為,同時將其他路由保留在 pages
目錄中以維持先前的行為。如果您的應用程式使用 pages
目錄,也請參閱 頁面路由器 (Pages Router) 文件。
注意事項:應用程式路由器的優先順序高於頁面路由器。跨目錄的路由不應解析為相同的 URL 路徑,否則會導致建置時錯誤以防止衝突。


預設情況下,app
內的元件是 React 伺服器元件。這是一種效能優化,可讓您輕鬆採用它們,您也可以使用 客戶端元件 (Client Components)。
建議:如果您不熟悉伺服器元件,請查看 伺服器 頁面。
資料夾和檔案的角色
Next.js 使用基於檔案系統的路由器,其中
- 資料夾用於定義路由。路由是由巢狀資料夾組成的單一路徑,遵循檔案系統階層結構,從根資料夾向下到包含
page.js
檔案的最終葉資料夾。請參閱 定義路由。 - 檔案用於建立顯示路由區段的使用者介面。請參閱特殊檔案。
路由區段
Defining Routes
Learn how to create your first route in Next.js.
Pages
Create your first page in Next.js
Layouts and Templates
Create your first shared layout in Next.js.
Linking and Navigating
Learn how navigation works in Next.js, and how to use the Link Component and `useRouter` hook.
Error Handling
Learn how to display expected errors and handle uncaught exceptions.
Loading UI and Streaming
Built on top of Suspense, Loading UI allows you to create a fallback for specific route segments, and automatically stream content as it becomes ready.
Redirecting
Learn the different ways to handle redirects in Next.js.
Route Groups
Route Groups can be used to partition your Next.js application into different sections.
Project Organization
Learn how to organize your Next.js project and colocate files.
Dynamic Routes
Dynamic Routes can be used to programmatically generate route segments from dynamic data.
Parallel Routes
Simultaneously render one or more pages in the same view that can be navigated independently. A pattern for highly dynamic applications.
Intercepting Routes
Use intercepting routes to load a new route within the current layout while masking the browser URL, useful for advanced routing patterns such as modals.
Route Handlers
Create custom request handlers for a given route using the Web's Request and Response APIs.
Middleware
Learn how to use Middleware to run code before a request is completed.
Internationalization
Add support for multiple languages with internationalized routing and localized content.
這有幫助嗎?