iT邦幫忙

0

使用Chatgpt學Next.js : [id].js & [id]資料夾

  • 分享至 

  • xImage
  •  

在 pages/posts/ 新增一個 [id].js 這個檔案?
還是新增一個[id]資料夾然後裡面再訪其他檔案?
還是都可以?

在 Next.js 中,您可以使用動態路由來創建以 [] 括起來的文件(例如 [id].js)或資料夾(例如 [id])來處理動態路由。這兩種方法都可以,但它們的用途和組織方式有所不同。讓我來解釋一下。

  1. 使用 [id].js 檔案
    當您在 pages/posts/ 目錄中創建一個名為 [id].js 的檔案時,這表示您希望根據路由的 id 參數來渲染頁面。例如:

/posts/1 會匹配 pages/posts/[id].js
/posts/2 也會匹配同一個檔案,但 params.id 會是 '2'
這是一種簡單的方式來處理單一的動態路由,通常適用於需要根據一個參數來顯示內容的情況。

  1. 使用 [id] 資料夾
    如果您在 pages/posts/ 目錄中創建一個名為 [id] 的資料夾,您可以在該資料夾中放置多個檔案來處理更複雜的情況。例如:
/pages/posts/[id]/index.js  // 對應 /posts/1
/pages/posts/[id]/edit.js   // 對應 /posts/1/edit
/pages/posts/[id]/delete.js // 對應 /posts/1/delete

這樣,您就可以在同一個資料夾下管理與特定 ID 相關的多個頁面。每個檔案都可以訪問到路由參數 id,這樣能讓您更清晰地組織代碼。

總結

使用 [id].js:適合簡單的動態路由,當您只需要根據一個參數來渲染頁面時使用。

使用 [id] 資料夾:當您需要組織多個與同一個參數相關的頁面時,使用資料夾會更方便且清晰。

範例
以下是一個簡單的範例來顯示如何使用這兩種方法:

使用 [id].js 檔案

// pages/posts/[id].js
import React from 'react';

const Post = ({ post }) => {
  return (
    <div>
      <h1>{post.title}</h1>
      <p>{post.content}</p>
    </div>
  );
};

// 獲取靜態路徑
export async function getStaticPaths() {
  const paths = [
    { params: { id: '1' } },
    { params: { id: '2' } },
  ];
  return { paths, fallback: false };
}

// 獲取靜態屬性
export async function getStaticProps({ params }) {
  const post = {
    id: params.id,
    title: `Post ${params.id}`,
    content: `這是 Post ${params.id} 的內容。`,
  };
  return { props: { post } };
}

export default Post;
javascript
// pages/posts/[id]/index.js
import React from 'react';

const Post = ({ post }) => {
  return (
    <div>
      <h1>{post.title}</h1>
      <p>{post.content}</p>
    </div>
  );
};

// 獲取靜態路徑
export async function getStaticPaths() {
  const paths = [
    { params: { id: '1' } },
    { params: { id: '2' } },
  ];
  return { paths, fallback: false };
}

// 獲取靜態屬性
export async function getStaticProps({ params }) {
  const post = {
    id: params.id,
    title: `Post ${params.id}`,
    content: `這是 Post ${params.id} 的內容。`,
  };
  return { props: { post } };
}

export default Post;

// pages/posts/[id]/edit.js

這樣可以讓您根據需求靈活使用這兩種方法!


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言