Next.js 14
此紀錄基於 Next.js 14 文檔。
Routing
特定檔名意義
在 Next.js 這個基於 file system 建構 route 的系統中,有一些 js 檔名具有特殊意義。
- layout.js
- template.js
- error.js
- loading.js
- not-found.js
- page.js
在同一個 route segment 的這些特殊檔案,會按照特定的層級渲染
<Layout>
<Template>
<ErrorBoundary fallback={<Error />}>
<Suspense fallback={<Loading />} />
<ErrorBoundary fallback={<NotFound />}>
<Page />
</ErrorBoundary>
</Suspense>
</ErrorBoundary>
</Template>
</Layout>
所以 ErrorBoundary 不會處理同一層級的 Layout/Template
template
看起來,在以上這樣 component 中,Template 是蠻特別的,以下簡單介紹。 如上可以發現,Layout 跟 Template 都包裹著 page。 而他們之間的差異是,Layout 可以在 route 改變時,持續保留狀態,Template 則是會隨著 route 改變重新 create component instance,也就是重 mount 的意思。
Next.js 文檔說明,在某些特定情況下,可能有需求會用到像 tempalte 這種,會隨著 route 改變而重 mount 的特性。e.g. logging page view