revalidateTag
revalidateTag
允许你按需清除特定缓存标签的 缓存数据。
要点:
revalidateTag
在 Node.js 和 Edge 运行时 中均可使用。revalidateTag
仅在下次访问路径时才会使缓存失效。这意味着对动态路由段调用revalidateTag
不会立即触发多次重新验证。失效操作仅在下次访问路径时发生。
参数
revalidateTag(tag: string): void;
tag
:一个字符串,表示与你想要重新验证的数据相关联的缓存标签。必须小于或等于 256 个字符。此值区分大小写。
你可以按如下方式向 fetch
添加标签:
fetch(url, { next: { tags: [...] } });
返回值
revalidateTag
不返回任何值。
示例
服务器操作
app/actions.ts
"use server";
import { revalidateTag } from "next/cache";
export default async function submit() {
await addPost();
revalidateTag("posts");
}
app/actions.js
"use server";
import { revalidateTag } from "next/cache";
export default async function submit() {
await addPost();
revalidateTag("posts");
}
路由处理程序
app/api/revalidate/route.ts
import type { NextRequest } from "next/server";
import { revalidateTag } from "next/cache";
export async function GET(request: NextRequest) {
const tag = request.nextUrl.searchParams.get("tag");
revalidateTag(tag);
return Response.json({ revalidated: true, now: Date.now() });
}
app/api/revalidate/route.js
import { revalidateTag } from "next/cache";
export async function GET(request) {
const tag = request.nextUrl.searchParams.get("tag");
revalidateTag(tag);
return Response.json({ revalidated: true, now: Date.now() });
}