Skip to content

revalidateTag

revalidateTag 允许你根据特定缓存标签按需使 缓存数据 失效。

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

用法

¥Usage

revalidateTag 可以在服务器函数和路由处理程序中调用。

¥revalidateTag can be called in Server Functions and Route Handlers.

revalidateTag 不能在客户端组件或中间件中调用,因为它只能在服务器环境中工作。

¥revalidateTag cannot be called in Client Components or Middleware, as it only works in server environments.

需要了解:revalidateTag 将标记的数据标记为过时,但只有在下次访问使用该标签的页面时才会获取新数据。这意味着调用 revalidateTag 不会立即触发多次重新验证。仅当下次访问使用该标签的任何页面时,才会发生失效。

¥Good to know: revalidateTag marks tagged data as stale, but fresh data is only fetched when pages using that tag are next visited. This means calling revalidateTag will not immediately trigger many revalidations at once. The invalidation only happens when any page using that tag 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 not exceed 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.

revalidatePath 的关系

¥Relationship with revalidatePath

revalidateTag 会使所有使用特定标签的页面中的数据失效,而 revalidatePath 会使特定页面或布局路径失效。

¥revalidateTag invalidates data with specific tags across all pages that use those tags, while revalidatePath invalidates specific page or layout paths.

需要了解:这些函数用途不同,可能需要一起使用才能实现全面的数据一致性。有关详细示例和注意事项,请参阅 与 revalidateTag 的关系

¥Good to know: These functions serve different purposes and may need to be used together for comprehensive data consistency. For detailed examples and considerations, see Relationship with revalidateTag.

示例

¥Examples

服务器动作

¥Server Action

ts
'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')

  if (tag) {
    revalidateTag(tag)
    return Response.json({ revalidated: true, now: Date.now() })
  }

  return Response.json({
    revalidated: false,
    now: Date.now(),
    message: 'Missing tag to revalidate',
  })
}