如何失效路由器缓存?
路由器缓存的失效分两条路径:服务端触发和客户端触发。在 Server Action 中调用 updateTag、revalidateTag、revalidatePath 都会自动通知客户端清除对应的路由器缓存——所以你不需要为路由器缓存单独做什么,管好数据缓存的失效就行。客户端的 router.refresh() 则是手动清除当前页面缓存的补充手段。
方法 1:Server Action 中使用 updateTag / revalidateTag(推荐)
在 Server Action 中调用失效 API 时,Next.js 会自动通知客户端清除对应的路由器缓存:
// app/actions.ts
"use server";
import { updateTag } from "next/cache";
export async function updatePost(id: string, formData: FormData) {
await db.post.update({
where: { id },
data: { title: formData.get("title") as string },
});
// 失效数据缓存 → 全路由缓存 → 路由器缓存(三层联动)
updateTag("posts");
updateTag(`post-${id}`);
}
这是最推荐的方式——一次调用,三层缓存全部失效。
方法 2:router.refresh()
在客户端组件中手动清除当前页面的路由器缓存: