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,你將看到以下輸出。

One

在瀏覽器中開啟 localhost:3000/posts/two,你將看到以下輸出。

Two
廣告
© . All rights reserved.