- Next.js 教程
- Next.js - 首頁
- Next.js - 概述
- Next.js - 環境設定
- Next.js 功能
- Next.js - 頁面
- Next.js - 靜態檔案服務
- Next.js - 元資料
- Next.js - CSS 支援
- Next.js - 全域性 CSS 支援
- Next.js - 預渲染
- Next.js 路由
- Next.js - 路由
- Next.js - 動態 API 路由
- Next.js - 命令式路由
- Next.js - 淺層路由
- Next.js API 路由
- Next.js - API 路由
- Next.js - API 中介軟體
- Next.js - 響應助手
- Next.js 其他內容
- Next.js - Typescript
- Next.js - 環境變數
- Next.js - 部署
- Next.js - CLI
- Next.js 有用資源
- Next.js - 快速指南
- Next.js - 有用資源
- Next.js - 討論
Next.js - 動態路由
在 Next.js 中,我們可以動態建立路由。在示例中,我們將動態建立頁面和它們的路由。
步驟 1. 定義 [id].js 檔案 − [id].js 表示動態頁面,其中 id 是相對路徑。在 pages/post 目錄中定義此檔案。
步驟 2. 定義 lib/posts.js − posts.js 表示 id 和內容。要建立 lib 目錄,放在根目錄中。
[id].js
使用 getStaticPaths() 方法更新 [id].js 檔案,該方法設定路徑並使用 getStaticProps() 方法來基於 id 獲取內容。
import Link from 'next/link'
import Head from 'next/head'
import Container from '../../components/container'
import { getAllPostIds, getPostData } from '../../lib/posts'
export default function Post({ postData }) {
return (
<Container>
{postData.id}
<br />
{postData.title}
<br />
{postData.date}
</Container>
)
}
export async function getStaticPaths() {
const paths = getAllPostIds()
return {
paths,
fallback: false
}
}
export async function getStaticProps({ params }) {
const postData = getPostData(params.id)
return {
props: {
postData
}
}
}
posts.js
posts.js 包含 getAllPostIds() 以獲取 id 和 getPostData() 以獲取相應的內容。
export function getPostData(id) {
const postOne = {
title: 'One',
id: 1,
date: '7/12/2020'
}
const postTwo = {
title: 'Two',
id: 2,
date: '7/12/2020'
}
if(id == 'one'){
return postOne;
}else if(id == 'two'){
return postTwo;
}
}
export function getAllPostIds() {
return [{
params: {
id: 'one'
}
},
{
params: {
id: 'two'
}
}
];
}
啟動 Next.js 伺服器
執行以下命令以啟動伺服器 -。
npm run dev > nextjs@1.0.0 dev \Node\nextjs > next ready - started server on https://:3000 event - compiled successfully event - build page: / wait - compiling... event - compiled successfully event - build page: /next/dist/pages/_error wait - compiling... event - compiled successfully
驗證輸出
在瀏覽器中開啟 localhost:3000/posts/one,你將看到以下輸出。
在瀏覽器中開啟 localhost:3000/posts/two,你將看到以下輸出。
廣告