自訂 App 元件

Next.js 使用 App 元件來初始化頁面。您可以覆寫它並控制頁面初始化,以及:

  • 在頁面切換時建立共享佈局
  • 向頁面注入額外數據
  • 添加全域 CSS

使用方法

要覆寫預設的 App,請建立 pages/_app 檔案,如下所示:

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 的資料獲取方法,例如 getStaticPropsgetServerSideProps

App 中使用 getInitialProps

App 中使用 getInitialProps 將會對沒有使用 getStaticProps 的頁面停用自動靜態優化 (Automatic Static Optimization)

我們不建議使用此模式。 相反,請考慮逐步採用 App Router,它讓您能更輕鬆地為頁面和佈局獲取資料。

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' }
}

On this page