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 回傳的資料在伺服器渲染時會被序列化。請確保 getInitialProps 回傳的物件是一個純粹的 Object,而不是使用 DateMapSet
  • 對於初始頁面載入,getInitialProps 只會在伺服器端執行。當使用 next/link 元件或 next/router 導航到不同路由時,getInitialProps 也會在客戶端執行。
  • 如果在自訂的 _app.js 中使用 getInitialProps,並且導航到的頁面使用 getServerSideProps,則 getInitialProps 也會在伺服器端執行。

上下文物件

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

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

注意事項

  • getInitialProps 只能在 pages/ 頂層檔案中使用,不能在巢狀元件中使用。若要在元件層級進行巢狀資料獲取,請考慮使用 App Router
  • 無論你的路由是靜態還是動態,從 getInitialProps 回傳的任何作為 props 的資料都可以在客戶端的初始 HTML 中被檢視。這是為了讓頁面能夠正確地進行 hydration。請確保不要在 props 中傳遞任何不應在客戶端出現的敏感資訊。

On this page