Next.js具有兩種形式的預(yù)渲染:靜態(tài)生成和服務(wù)器端渲染
getStaticProps
(靜態(tài)生成):在構(gòu)建時(shí)獲取數(shù)據(jù)戚炫。
getStaticPaths
(靜態(tài)生成):根據(jù)數(shù)據(jù)指定要[動(dòng)態(tài)]渲染的[動(dòng)態(tài)路由]作郭。
getServerSideProps
(服務(wù)器端渲染):在每個(gè)請(qǐng)求上獲取數(shù)據(jù)。
getStaticProps(靜態(tài)生成)
呈現(xiàn)頁面所需的數(shù)據(jù)可在構(gòu)建時(shí)在用戶請(qǐng)求之前獲得秀睛。
該頁面必須預(yù)渲染(對(duì)于SEO)并且必須非吵檀ⅲ快- getStaticProps生成HTML和JSON文件瓤檐,CDN可以將它們都緩存以提高性能登疗。
import { GetStaticProps } from 'next' // 對(duì)于TypeScript,您可以使用以下GetStaticProps類型next
export async function getStaticProps: GetStaticProps(context) {
return {
props: {}, // 將作為道具傳遞到頁面組件
}
}
getStaticPaths(靜態(tài)生成)
如果頁面具有動(dòng)態(tài)路由并使用 getStaticProps
它嫌蚤,則需要定義一個(gè)在構(gòu)建時(shí)必須呈現(xiàn)為HTML的路徑列表辐益。
如果從使用動(dòng)態(tài)路由的頁面導(dǎo)出async調(diào)用的函數(shù)getStaticPaths,則Next.js將靜態(tài)預(yù)呈現(xiàn)由指定的所有路徑getStaticPaths脱吱。
例如智政,假設(shè)有一個(gè)使用動(dòng)態(tài)路由的頁面pages/posts/[id].js。如果您getStaticPaths從此頁面導(dǎo)出并返回以下內(nèi)容paths:
getStaticPaths 僅在構(gòu)建時(shí)在服務(wù)器端運(yùn)行箱蝠。
export async function getStaticPaths() {
return {
paths: [
{ params: { id: '1' } },
{ params: { id: '2' } }
],
fallback: true or false
};
}
// 在使用 getStaticProps 靜態(tài)生成
export async function getStaticProps({ params }) {
// 參數(shù)包含post ' id '续捂。
// 如果路由類似/posts/1垦垂,則params。id是1
const res = await fetch(`https://.../posts/${params.id}`)
const post = await res.json()
// 通過道具將post數(shù)據(jù)傳遞到頁面
return { props: { post } }
}
getServerSideProps(服務(wù)器端渲染)
getServerSideProps僅在服務(wù)器端運(yùn)行牙瓢,而從不在瀏覽器上運(yùn)行劫拗。
getServerSideProps 比 getStaticProp 花的時(shí)間要慢由于服務(wù)器必須在每個(gè)請(qǐng)求上計(jì)算結(jié)果,并且如果沒有額外的配置矾克,結(jié)果不能由CDN緩存页慷。
如果不需要預(yù)渲染數(shù)據(jù),則應(yīng)考慮在客戶端獲取數(shù)據(jù)胁附。
import { GetServerSideProps } from 'next' //TypeScript:使用 GetServerSideProps
export async function getServerSideProps:GetServerSideProps (context) {
return {
props: {}, // 將作為道具傳遞到頁面組件
}
}