Skip to content

revalidateTag

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

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

需要了解:

¥Good to know:

  • 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

tsx
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:

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

返回

¥Returns

revalidateTag 不返回值。

¥revalidateTag does not return a value.

示例

¥Examples

服务器动作

¥Server Action

ts
'use server'

import { revalidateTag } from 'next/cache'

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

import { revalidateTag } from 'next/cache'

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

路由处理程序

¥Route Handler

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

Next.js v15.2 中文网 - 粤ICP备13048890号