在學(xué)習(xí) Next.js 應(yīng)用程序路由器的過程中,實(shí)踐是非常重要的一環(huán)。通過實(shí)際操作和示例,你可以更好地理解和掌握其功能和用法。以下是一些實(shí)踐建議和示例,幫助你深入學(xué)習(xí)。
以下是一個(gè)使用 Next.js 應(yīng)用程序路由器創(chuàng)建簡單博客應(yīng)用的示例。
my-app/
├─ app/
│ ├─ blog/
│ │ ├─ page.js
│ │ ├─ [slug]/page.js
│ ├─ layout.js
├─ public/
├─ package.json
app/layout.js
):export default function RootLayout({ children }) {
return (
<html lang="zh">
<body>
<nav>
<a href="/">編程獅首頁</a>
<a href="/blog">編程獅博客</a>
</nav>
{children}
</body>
</html>
);
}
app/blog/page.js
):export default async function BlogPage() {
// 模擬數(shù)據(jù)獲取
const posts = await fetch('https://api.example.com/posts').then(res => res.json());
return (
<div>
<h1>編程獅博客列表</h1>
<ul>
{posts.map(post => (
<li key={post.id}>
<a href={`/blog/${post.slug}`}>{post.title}</a>
</li>
))}
</ul>
</div>
);
}
app/blog/[slug]/page.js
):export default async function BlogPostPage({ params }) {
// 從 params 中獲取 slug
const { slug } = params;
// 模擬數(shù)據(jù)獲取
const post = await fetch(`https://api.example.com/posts/${slug}`).then(res => res.json());
return (
<div>
<h1>{post.title}</h1>
<p>{post.content}</p>
</div>
);
}
以下是一個(gè)使用 Next.js 應(yīng)用程序路由器處理表單提交的示例。
app/contact/page.js
):export default function ContactPage() {
async function handleSubmit(formData) {
// 處理表單數(shù)據(jù)
const response = await fetch('/api/send-email', {
method: 'POST',
body: JSON.stringify(Object.fromEntries(formData)),
});
if (!response.ok) {
throw new Error('表單提交失敗');
}
return { message: '表單提交成功' };
}
return (
<form action={handleSubmit}>
<label htmlFor="name">姓名:</label>
<input type="text" id="name" name="name" required />
<label htmlFor="email">郵箱:</label>
<input type="email" id="email" name="email" required />
<label htmlFor="message">消息:</label>
<textarea id="message" name="message" required />
<button type="submit">提交</button>
</form>
);
}
通過以上示例和實(shí)踐建議,你可以更好地理解和掌握 Next.js 應(yīng)用程序路由器的使用方法。不斷實(shí)踐和探索,你將能夠構(gòu)建出功能強(qiáng)大的應(yīng)用程序。
更多建議: