ข้ามไปยังเนื้อหา

Dynamic Pages from Data

Next.js App Router ใช้ generateStaticParams() เพื่อระบุ dynamic routes ตอน build time Next Pages Router ใช้ getStaticPaths() Astro ใช้ getStaticPaths() ในไฟล์ [slug].astro ชื่อเดียวกันกับ Pages Router แต่ pattern ต่างกันเล็กน้อย คุณ export async function getStaticPaths ที่คืนค่า array ของ object { params } (optionally พร้อม props)

ต้องใช้โปรเจกต์ Astro เต็มรูปแบบ ใช้ npm create astro@latest เพื่อสร้างโปรเจกต์

React
// app/blog/[slug]/page.tsx (Next.js App Router)
import { allPosts } from 'contentlayer/generated';
export async function generateStaticParams() {
return allPosts.map((post) => ({ slug: post.slugAsParams }));
}
export default function PostPage({ params }: { params: { slug: string } }) {
const post = allPosts.find((p) => p.slugAsParams === params.slug)!;
return (
<article>
<h1>{post.title}</h1>
<p>{post.description}</p>
</article>
);
}
Astro
---
// src/pages/blog/[slug].astro (Astro)
import { getCollection, render } from 'astro:content';
export async function getStaticPaths() {
const posts = await getCollection('blog');
return posts.map((entry) => ({
params: { slug: entry.slug },
props: { entry },
}));
}
const { entry } = Astro.props;
const { Content } = await render(entry);
---
<article>
<h1>{entry.data.title}</h1>
<p>{entry.data.description}</p>
<Content />
</article>

Astro ส่ง props พร้อมกับ params — ทำให้ page component รับ entry ได้โดยตรงจาก Astro.props โดยไม่ต้อง look up ซ้ำอีกครั้ง

React
// pages/blog/[slug].tsx (Next.js Pages Router)
import { allPosts } from 'contentlayer/generated';
import { useMDXComponent } from 'next-contentlayer/hooks';
export async function getStaticPaths() {
return {
paths: allPosts.map((p) => ({ params: { slug: p.slugAsParams } })),
fallback: false,
};
}
export async function getStaticProps({ params }) {
const post = allPosts.find((p) => p.slugAsParams === params.slug)!;
return { props: { post } };
}
export default function PostPage({ post }) {
const MDXContent = useMDXComponent(post.body.code);
return (
<article>
<h1>{post.title}</h1>
<MDXContent />
</article>
);
}
Astro
---
// src/pages/blog/[slug].astro (Astro — same file handles both path gen + rendering)
import { getCollection, render } from 'astro:content';
export async function getStaticPaths() {
const posts = await getCollection('blog');
return posts.map((entry) => ({
params: { slug: entry.slug },
props: { entry }, // props flow directly into Astro.props
}));
}
const { entry } = Astro.props; // typed from your zod schema
const { Content } = await render(entry);
---
<article>
<h1>{entry.data.title}</h1>
<Content />
</article>

ใน Next.js Pages Router ต้องใช้ทั้ง getStaticPaths และ getStaticProps แยกกัน Astro รวมทั้งสองไว้ในไฟล์เดียวกันโดยการส่ง props ใน getStaticPaths return value

`getStaticPaths()` อยู่ที่ไหนในโปรเจกต์ Astro?
แต่ละ object ในอาร์เรย์ที่ `getStaticPaths` คืนค่าแทนอะไร?
อะไรคือ equivalent ของ Next App Router `generateStaticParams` ใน Astro?