自訂 App 元件

Next.js 使用 App 元件來初始化頁面。您可以覆寫它並控制頁面初始化,同時實現以下功能:

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

使用方法

要覆寫預設的 App,請按照以下方式建立 pages/_app 檔案:

import type { AppProps } from 'next/app'

export default function MyApp({ Component, pageProps }: AppProps) {
  return <Component {...pageProps} />
}
export default function MyApp({ Component, pageProps }) {
  return <Component {...pageProps} />
}

Component 屬性代表當前活動的 page,因此當您在路由之間導航時,Component 會切換為新的 page。因此,您傳遞給 Component 的任何屬性都會被 page 接收。

pageProps 是一個物件,包含透過我們的資料獲取方法為您的頁面預先載入的初始屬性,如果沒有則為空物件。

重要須知

  • 如果您的應用程式正在運行且添加了自訂 App,則需要重新啟動開發伺服器。僅在 pages/_app.js 之前不存在時才需要此操作。
  • App 不支援 Next.js 的資料獲取方法,例如 getStaticPropsgetServerSideProps

App 中使用 getInitialProps

App 中使用 getInitialProps 會對未使用 getStaticProps 的頁面禁用自動靜態優化

我們不建議使用此模式。 相反,請考慮逐步採用 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' }
}
import App from 'next/app'

export default function MyApp({ Component, pageProps, example }) {
  return (
    <>
      <p>Data: {example}</p>
      <Component {...pageProps} />
    </>
  )
}

MyApp.getInitialProps = async (context) => {
  const ctx = await App.getInitialProps(context)

  return { ...ctx, example: 'data' }
}