实战案例:博客编辑的完整缓存策略(续)
// app/actions.ts — Server Action
"use server";
import { updateTag } from "next/cache";
import { redirect } from "next/navigation";
export async function updatePost(id: string, formData: FormData) {
// 1. 更新数据库
await db.post.update({
where: { id },
data: {
title: formData.get("title") as string,
content: formData.get("content") as string,
},
});
// 2. 一次调用,四层缓存全部处理:
// - 第 1 层(请求记忆):下次请求自动重新获取
// - 第 2 层(数据缓存):updateTag 立即失效
// - 第 3 层(全路由缓存):跟着数据缓存失效
// - 第 4 层(路由器缓存):Server Action 自动通知客户端
updateTag("posts");
updateTag(`post-${id}`);
// 3. 重定向到详情页(用户立刻看到新数据)
redirect(`/posts/${id}`);
}