Building A Simple CRUD API With Next.Js 13
import { useState } from 'react';
import Link from 'next/link';
import { useRouter }s next/router';
// 假设我们有一个API客户端来处理HTTP请求
import { apiClient } from '../../lib/api-client';
export default function PostsPage({ posts }) {
const router = useRouter();
const [isLoading, setIsLoading] = useState(false);
const handleDelete = async (id) => {
if (window.confirm('Are you sure you want to delete this post?')) {
setIsLoading(true);
try {
await apiClient.delete(`/posts/${id}`);
router.replace(router.asPath);
} catch (error) {
alert('Failed to delete post');
} finally {
setIsLoading(false);
}
}
};
return (
<div>
<h1>Posts</h1>
<p>
<Link href="/posts/new">
<a>New Post</a>
</Link>
</p>
<ul>
{posts.map((post) => (
<li key={post.id}>
<Link href={`/posts/${post.id}`}>
<a>{post.title}</a>
</Link>
<button onClick={() => handleDelete(post.id)} disabled={isLoading}>
{isLoading ? 'Deleting...' : 'Delete'}
</button>
</li>
))}
</ul>
</div>
);
}
// 在页面加载时获取帖子
export async function getServerSideProps() {
try {
const { data: posts } = await apiClient.get('/posts');
return { props: { posts } };
} catch (error) {
return { props: { posts: [] } };
}
}
这个代码示例展示了如何使用Next.js 13创建一个简单的CRUD API应用。它使用了客户端路由,以及在服务器端获取初始数据。注意,示例中的apiClient
是假设存在的,需要在项目中实现相应的API客户端逻辑。
评论已关闭