實作 getStaticPaths
首先,讓我們設定檔案結構:
- 在
pages/posts
目錄下建立一個名為[id].js
的檔案。 - 同時,刪除
pages/posts
目錄中的first-post.js
— 我們將不再使用這個檔案。
接著,在編輯器中開啟 pages/posts/[id].js
並貼上以下程式碼。我們稍後會填寫 ...
的部分:
import Layout from '../../components/layout';
export default function Post() {
return <Layout>...</Layout>;
}
然後,開啟 lib/posts.js
並在檔案底部新增以下 getAllPostIds
函式。它會回傳 posts
目錄中的檔案名稱清單(排除 .md
副檔名):
export function getAllPostIds() {
const fileNames = fs.readdirSync(postsDirectory);
// 回傳的陣列格式如下:
// [
// {
// params: {
// id: 'ssg-ssr'
// }
// },
// {
// params: {
// id: 'pre-rendering'
// }
// }
// ]
return fileNames.map((fileName) => {
return {
params: {
id: fileName.replace(/\.md$/, ''),
},
};
});
}
重要:回傳的清單 不 只是字串陣列 — 它 必須 是如上方註解所示格式的物件陣列。每個物件都必須包含 params
鍵,且其中要有 id
鍵(因為我們在檔案名稱中使用了 [id]
)。否則,getStaticPaths
將會執行失敗。
最後,我們將匯入 getAllPostIds
函式並在 getStaticPaths
中使用它。開啟 pages/posts/[id].js
並在匯出的 Post
元件前複製以下程式碼:
import { getAllPostIds } from '../../lib/posts';
export async function getStaticPaths() {
const paths = getAllPostIds();
return {
paths,
fallback: false,
};
}
paths
包含由getAllPostIds()
回傳的已知路徑陣列,其中包含由pages/posts/[id].js
定義的參數。詳細資訊請參閱paths
鍵文件- 目前先忽略
fallback: false
— 我們稍後會解釋這個設定。
我們快完成了 — 但還需要實作 getStaticProps
。讓我們在下一頁繼續!