Skip to main content

revalidateTag

revalidateTag 允许你按需清除 缓存数据 以获取特定缓存标记。

¥revalidateTag allows you to purge cached data on-demand for a specific cache tag.

很高兴知道:

¥Good to know:

  • revalidateTagNode.js 和 Edge 运行时 中均可用。

    ¥revalidateTag is available in both Node.js and Edge runtimes.

  • revalidateTag 仅在下次访问该路径时使缓存无效。这意味着使用动态路由段调用 revalidateTag 不会立即触发多次重新验证。仅当下次访问该路径时才会发生失效。

    ¥revalidateTag only invalidates the cache when the path is next visited. This means calling revalidateTag with a dynamic route segment will not immediately trigger many revalidations at once. The invalidation only happens when the path is next visited.

参数

¥Parameters

revalidateTag(tag: string): void;
  • tag:表示与要重新验证的数据关联的缓存标记的字符串。必须小于或等于 256 个字符。该值区分大小写。

    ¥tag: A string representing the cache tag associated with the data you want to revalidate. Must be less than or equal to 256 characters. This value is case-sensitive.

你可以向 fetch 添加标签,如下所示:

¥You can add tags to fetch as follows:

fetch(url, { next: { tags: [...] } });

返回

¥Returns

revalidateTag 不返回任何值。

¥revalidateTag does not return any value.

示例

¥Examples

服务器动作

¥Server Action

'use server'

import { revalidateTag } from 'next/cache'

export default async function submit() {
await addPost()
revalidateTag('posts')
}
'use server'

import { revalidateTag } from 'next/cache'

export default async function submit() {
await addPost()
revalidateTag('posts')
}

路由处理程序

¥Route Handler

import { 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() })
}
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() })
}