跳到內容
API 參考函數getInitialProps

getInitialProps

須知getInitialProps 是一個舊版的 API。我們建議改用 getStaticPropsgetServerSideProps

getInitialProps 是一個 async 函數,可以新增到頁面的預設匯出 React 元件。它會在伺服器端執行,並且在頁面轉換期間再次於客戶端執行。函數的結果將會以 props 的形式轉發到 React 元件。

pages/index.tsx
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 也會在伺服器上執行。

Context 物件

getInitialProps 接收一個名為 context 的單一引數,它是一個具有以下屬性的物件

名稱描述
pathname目前的路由,頁面在 /pages 中的路徑
queryURL 的查詢字串,解析為物件
asPath瀏覽器中顯示的實際路徑 (包含查詢) 的 String
reqHTTP 請求物件 (僅限伺服器端)
resHTTP 回應物件 (僅限伺服器端)
err如果在渲染期間遇到任何錯誤,則為錯誤物件

注意事項

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