伺服器端渲染 (SSR)
也稱為“SSR”或“動態渲染”。
如果一個頁面使用伺服器端渲染,則頁面 HTML 會在每次請求時生成。
要在頁面上使用伺服器端渲染,您需要匯出一個名為getServerSideProps的async函式。此函式將在每次請求時由伺服器呼叫。
例如,假設您的頁面需要預渲染頻繁更新的資料(從外部 API 獲取)。您可以編寫getServerSideProps來獲取此資料並將其傳遞給Page,如下所示
export default function Page({ data }) {
// Render data...
}
// This gets called on every request
export async function getServerSideProps() {
// Fetch data from external API
const res = await fetch(`https://.../data`)
const data = await res.json()
// Pass data to the page via props
return { props: { data } }
}如您所見,getServerSideProps類似於getStaticProps,但區別在於getServerSideProps在每次請求時執行,而不是在構建時執行。
要了解有關getServerSideProps工作原理的更多資訊,請檢視我們的資料獲取文件。
這有幫助嗎?