getServerSideProps
當從頁面匯出名為 getServerSideProps
(伺服器端渲染) 的函數時,Next.js 會在每次請求時預先渲染此頁面,並使用 getServerSideProps
傳回的資料。如果您想要抓取經常變更的資料,並讓頁面更新以顯示最新的資料,這會很有用。
pages/index.tsx
import type { InferGetServerSidePropsType, GetServerSideProps } from 'next'
type Repo = {
name: string
stargazers_count: number
}
export const getServerSideProps = (async () => {
// Fetch data from external API
const res = await fetch('https://api.github.com/repos/vercel/next.js')
const repo: Repo = await res.json()
// Pass data to the page via props
return { props: { repo } }
}) satisfies GetServerSideProps<{ repo: Repo }>
export default function Page({
repo,
}: InferGetServerSidePropsType<typeof getServerSideProps>) {
return (
<main>
<p>{repo.stargazers_count}</p>
</main>
)
}
您可以在頂層範圍中匯入模組,以在 getServerSideProps
中使用。使用的匯入模組將不會為客戶端捆綁。這表示您可以直接在 getServerSideProps
中編寫伺服器端程式碼,包括從您的資料庫抓取資料。
Context 參數
context
參數是一個物件,包含以下鍵
名稱 | 描述 |
---|---|
params | 如果此頁面使用動態路由,則 params 包含路由參數。如果頁面名稱為 [id].js ,則 params 看起來會像 { id: ... } 。 |
req | HTTP IncomingMessage 物件,具有額外的 cookies 屬性,這是一個物件,其字串鍵對應到 Cookie 的字串值。 |
res | HTTP 回應物件. |
query | 一個代表查詢字串的物件,包括動態路由參數。 |
preview | (已棄用,改用 draftMode ) 如果頁面處於預覽模式,則 preview 為 true ,否則為 false 。 |
previewData | (已棄用,改用 draftMode ) 由 setPreviewData 設定的預覽資料集。 |
draftMode | 如果頁面處於草稿模式,則 draftMode 為 true ,否則為 false 。 |
resolvedUrl | 請求 URL 的正規化版本,它會移除用戶端轉換的 _next/data 前綴,並包含原始查詢值。 |
locale | 包含活動地區設定(如果已啟用)。 |
locales | 包含所有支援的地區設定(如果已啟用)。 |
defaultLocale | 包含已設定的預設地區設定(如果已啟用)。 |
getServerSideProps 傳回值
getServerSideProps
函數應傳回一個物件,其中包含下列任何一個屬性
props
props
物件是一個鍵值對,其中每個值都由頁面元件接收。它應該是一個可序列化的物件,以便任何傳遞的 props 都可以使用 JSON.stringify
進行序列化。
export async function getServerSideProps(context) {
return {
props: { message: `Next.js is awesome` }, // will be passed to the page component as props
}
}
notFound
notFound
布林值允許頁面傳回 404
狀態和 404 頁面。使用 notFound: true
,即使之前有成功產生的頁面,頁面仍會傳回 404
。這旨在支援使用者產生內容被其作者移除等使用案例。
export async function getServerSideProps(context) {
const res = await fetch(`https://.../data`)
const data = await res.json()
if (!data) {
return {
notFound: true,
}
}
return {
props: { data }, // will be passed to the page component as props
}
}
redirect
redirect
物件允許重新導向到內部和外部資源。它應符合 { destination: string, permanent: boolean }
的形狀。在某些罕見的情況下,您可能需要為較舊的 HTTP
用戶端指定自訂狀態碼才能正確重新導向。在這些情況下,您可以使用 statusCode
屬性來代替 permanent
屬性,但不能同時使用兩者。
export async function getServerSideProps(context) {
const res = await fetch(`https://.../data`)
const data = await res.json()
if (!data) {
return {
redirect: {
destination: '/',
permanent: false,
},
}
}
return {
props: {}, // will be passed to the page component as props
}
}
版本歷史
版本 | 變更 |
---|---|
v13.4.0 | App Router 現在已穩定,並簡化了資料獲取 |
v10.0.0 | 新增了 locale 、locales 、defaultLocale 和 notFound 選項。 |
v9.3.0 | 引入了 getServerSideProps 。 |
這有幫助嗎?