// posts will be populated at build time by getStaticProps()exportdefaultfunctionBlog({ posts }) {return ( <ul> {posts.map((post) => ( <li>{post.title}</li> ))} </ul> )}// This function gets called at build time on server-side.// It won't be called on client-side, so you can even do// direct database queries.exportasyncfunctiongetStaticProps() {// Call an external API endpoint to get posts.// You can use any data fetching libraryconstres=awaitfetch('https://.../posts')constposts=awaitres.json()// By returning { props: { posts } }, the Blog component// will receive `posts` as a prop at build timereturn { props: { posts, }, }}
// The following function is shared// with getStaticProps and API routes// from a `lib/` directoryexportasyncfunctionloadPosts() {// Call an external API endpoint to get postsconstres=awaitfetch('https://.../posts/')constdata=awaitres.json()return data}
pages/blog.js
// pages/blog.jsimport { loadPosts } from'../lib/load-posts'// This function runs only on the server sideexportasyncfunctiongetStaticProps() {// Instead of fetching your `/api` route you can call the same// function directly in `getStaticProps`constposts=awaitloadPosts()// Props returned will be passed to the page componentreturn { props: { posts } }}
或者,如果您**不**使用 API 路由來提取數據,則可以在 getStaticProps 中直接使用 fetch() API 來提取數據。