getInitialProps

重要提示getInitialProps 是一個舊版 API。建議改用 getStaticPropsgetServerSideProps

getInitialProps 是一個 async 函式,可以添加到頁面預設匯出的 React 元件中。它會在伺服器端執行,並在頁面轉換時再次在客戶端執行。函式的執行結果將作為 props 傳遞給 React 元件。

import { NextPageContext } from 'next'

Page.getInitialProps = async (ctx: NextPageContext) => {
  const res = await fetch('https://api.github.com/repos/vercel/next.js')
  const json = await res.json()
  return { stars: json.stargazers_count }
}

export default function Page({ stars }: { stars: number }) {
  return stars
}

重要提示

  • getInitialProps 返回的資料在伺服器渲染時會被序列化。請確保返回的物件是一個純粹的 Object,而不是使用 DateMapSet
  • 對於初始頁面載入,getInitialProps 僅在伺服器端執行。當使用 next/link 元件或 next/router 導航到其他路由時,getInitialProps 也會在客戶端執行。
  • 如果在自訂的 _app.js 中使用了 getInitialProps,並且導航到的頁面使用了 getServerSideProps,那麼 getInitialProps 也會在伺服器端執行。

Context 物件

getInitialProps 接收一個名為 context 的參數,這是一個包含以下屬性的物件:

名稱描述
pathname當前路由,即 /pages 中頁面的路徑
queryURL 的查詢字串,解析為物件
asPath瀏覽器中顯示的實際路徑(包括查詢字串)的字串
reqHTTP 請求物件(僅伺服器端)
resHTTP 回應物件(僅伺服器端)
err渲染過程中遇到的錯誤物件

注意事項

  • getInitialProps 只能在 pages/ 頂層檔案中使用,不能在巢狀元件中使用。如果需要在元件層級進行巢狀資料獲取,請考慮使用 App Router
  • 無論您的路由是靜態還是動態,從 getInitialProps 返回的任何作為 props 的資料都可以在客戶端的初始 HTML 中檢查。這是為了確保頁面能夠正確水合 (hydrate)。請確保不要在 props 中傳遞任何不應在客戶端可用的敏感資訊。

On this page