getStaticPaths
如果頁面具有動態路由並使用 getStaticProps
,則需要定義要靜態產生的路徑列表。
當您從使用動態路由的頁面匯出名為 getStaticPaths
(靜態網站產生) 的函式時,Next.js 將靜態預先渲染 getStaticPaths
指定的所有路徑。
pages/repo/[name].tsx
import type {
InferGetStaticPropsType,
GetStaticProps,
GetStaticPaths,
} from 'next'
type Repo = {
name: string
stargazers_count: number
}
export const getStaticPaths = (async () => {
return {
paths: [
{
params: {
name: 'next.js',
},
}, // See the "paths" section below
],
fallback: true, // false or "blocking"
}
}) satisfies GetStaticPaths
export const getStaticProps = (async (context) => {
const res = await fetch('https://api.github.com/repos/vercel/next.js')
const repo = await res.json()
return { props: { repo } }
}) satisfies GetStaticProps<{
repo: Repo
}>
export default function Page({
repo,
}: InferGetStaticPropsType<typeof getStaticProps>) {
return repo.stargazers_count
}
getStaticPaths
API 參考涵蓋了可以與 getStaticPaths
一起使用的所有參數和屬性。
我應該何時使用 getStaticPaths?
如果您要靜態預先渲染使用動態路由的頁面,且符合以下條件,則應使用 getStaticPaths
:
- 資料來自無頭 CMS
- 資料來自資料庫
- 資料來自檔案系統
- 資料可以公開快取(非使用者特定)
- 頁面必須預先渲染(為了 SEO)並且速度非常快 —
getStaticProps
產生HTML
和JSON
檔案,兩者都可以被 CDN 快取以提高效能
getStaticPaths 何時執行
getStaticPaths
只會在生產環境的建置期間執行,不會在執行階段呼叫。您可以使用此工具驗證寫在 getStaticPaths
內的程式碼已從用戶端捆綁包中移除。
getStaticProps 如何根據 getStaticPaths 執行
getStaticProps
會在next build
期間針對建置期間傳回的任何paths
執行- 使用
fallback: true
時,getStaticProps
會在背景執行 - 使用
fallback: blocking
時,getStaticProps
會在初始渲染之前呼叫
我可以在哪裡使用 getStaticPaths
getStaticPaths
必須 與getStaticProps
一起使用- 您不能將
getStaticPaths
與getServerSideProps
一起使用 - 您可以從也使用
getStaticProps
的動態路由匯出getStaticPaths
- 您不能從非頁面檔案(例如您的
components
資料夾)匯出getStaticPaths
- 您必須將
getStaticPaths
匯出為獨立函式,而不是頁面元件的屬性
在開發環境中,每次請求都會執行
在開發環境 (next dev
) 中,每次請求都會呼叫 getStaticPaths
。
隨需產生路徑
getStaticPaths
讓您可以控制在建置期間產生哪些頁面,而不是透過 fallback
隨需產生。在建置期間產生更多頁面會導致建置速度變慢。
您可以透過為 paths
傳回空陣列來延遲隨需產生所有頁面。當您將 Next.js 應用程式部署到多個環境時,這特別有幫助。例如,您可以透過隨需產生所有頁面以進行預覽(但不適用於生產環境建置)來加快建置速度。這對於具有數百/數千個靜態頁面的網站很有幫助。
pages/posts/[id].js
export async function getStaticPaths() {
// When this is true (in preview environments) don't
// prerender any static pages
// (faster builds, but slower initial page load)
if (process.env.SKIP_BUILD_STATIC_GENERATION) {
return {
paths: [],
fallback: 'blocking',
}
}
// Call an external API endpoint to get posts
const res = await fetch('https://.../posts')
const posts = await res.json()
// Get the paths we want to prerender based on posts
// In production environments, prerender all pages
// (slower builds, but faster initial page load)
const paths = posts.map((post) => ({
params: { id: post.id },
}))
// { fallback: false } means other routes should 404
return { paths, fallback: false }
}
這有幫助嗎?