自訂應用程式 (Custom App)
Next.js 使用 App
組件來初始化頁面。您可以覆寫它並控制頁面初始化和
- 在頁面變更之間建立共用佈局
- 將額外資料注入頁面
- 新增全域 CSS
用法 (Usage)
要覆寫預設的 App
,請如下所示建立 pages/_app
檔案
pages/_app.tsx
import type { AppProps } from 'next/app'
export default function MyApp({ Component, pageProps }: AppProps) {
return <Component {...pageProps} />
}
Component
屬性是作用中的 page
,因此每當您在路由之間導航時,Component
都會變更為新的 page
。 因此,您傳送到 Component
的任何屬性都會由 page
接收。
pageProps
是一個物件,包含透過我們的資料提取方法 預先載入到頁面的初始屬性,否則它是一個空物件。
注意事項:
- 如果您的應用程式正在執行,並且您新增了自訂
App
,則需要重新啟動開發伺服器。僅在之前不存在pages/_app.js
時才需要。App
不支援 Next.js 的資料提取方法,例如getStaticProps
或getServerSideProps
。
在 App
中使用 getInitialProps
在 App
中使用 getInitialProps
將會為沒有 getStaticProps
的頁面停用 自動靜態最佳化。
**我們不建議使用這種模式。** 建議您考慮逐步採用 App Router,它可以讓您更輕鬆地為頁面和佈局提取資料。
pages/_app.tsx
import App, { AppContext, AppInitialProps, AppProps } from 'next/app'
type AppOwnProps = { example: string }
export default function MyApp({
Component,
pageProps,
example,
}: AppProps & AppOwnProps) {
return (
<>
<p>Data: {example}</p>
<Component {...pageProps} />
</>
)
}
MyApp.getInitialProps = async (
context: AppContext
): Promise<AppOwnProps & AppInitialProps> => {
const ctx = await App.getInitialProps(context)
return { ...ctx, example: 'data' }
}
這有幫助嗎?