跳到内容

updateTag

updateTag 允许您在 服务器操作 中按需更新特定缓存标签的缓存数据

此函数专为**读写一致性**场景设计,即用户进行更改(例如创建帖子)后,UI 会立即显示更改,而不是陈旧数据。

用法

updateTag **只能**在 服务器操作 中调用。它不能在路由处理器、客户端组件或任何其他上下文中使用。

如果您需要在路由处理器或其他上下文中使缓存标签失效,请改用 revalidateTag

**须知**:updateTag 会立即使指定标签的缓存数据过期。下一次请求将等待获取新鲜数据,而不是从缓存中提供陈旧内容,确保用户立即看到他们的更改。

参数

updateTag(tag: string): void;
  • tag:一个字符串,表示您要更新的数据所关联的缓存标签。不得超过 256 个字符。此值区分大小写。

标签必须首先分配给缓存数据。您可以通过两种方式执行此操作:

  • 使用 next.tags 选项与 fetch 来缓存外部 API 请求
fetch(url, { next: { tags: ['posts'] } })
  • 在带有 'use cache' 指令的缓存函数或组件内部使用 cacheTag
import { cacheTag } from 'next/cache'
 
async function getData() {
  'use cache'
  cacheTag('posts')
  // ...
}

返回

updateTag 不返回任何值。

与 revalidateTag 的区别

虽然 updateTagrevalidateTag 都使缓存数据失效,但它们服务于不同的目的:

  • updateTag:

    • 只能在服务器操作中使用
    • 下一次请求等待新鲜数据(不提供陈旧内容)
    • 专为读写一致性场景设计
  • revalidateTag:

    • 可在服务器操作和路由处理器中使用
    • 使用 profile="max"(推荐):在后台获取新鲜数据的同时提供缓存数据(先陈旧再重新验证)
    • 使用自定义配置文件:可配置为任何缓存生命周期配置文件以进行高级使用
    • 不带配置文件:与 updateTag 等效的旧版行为

示例

具有读写一致性(Read-Your-Own-Writes)的服务器操作

app/actions.ts
'use server'
 
import { updateTag } from 'next/cache'
import { redirect } from 'next/navigation'
 
export async function createPost(formData: FormData) {
  const title = formData.get('title')
  const content = formData.get('content')
 
  // Create the post in your database
  const post = await db.post.create({
    data: { title, content },
  })
 
  // Invalidate cache tags so the new post is immediately visible
  // 'posts' tag: affects any page that displays a list of posts
  updateTag('posts')
  // 'post-{id}' tag: affects the individual post detail page
  updateTag(`post-${post.id}`)
 
  // Redirect to the new post - user will see fresh data, not cached
  redirect(`/posts/${post.id}`)
}

在服务器操作之外使用时出错

app/api/posts/route.ts
import { updateTag } from 'next/cache'
 
export async function POST() {
  // This will throw an error
  updateTag('posts')
  // Error: updateTag can only be called from within a Server Action
 
  // Use revalidateTag instead in Route Handlers
  revalidateTag('posts', 'max')
}

何时使用 updateTag

在以下情况使用 updateTag

  • 您正在服务器操作中
  • 您需要立即缓存失效以实现读写一致性
  • 您希望确保下一个请求看到更新的数据

在以下情况改用 revalidateTag

  • 您在路由处理器或其他非操作上下文中
  • 您想要先陈旧再重新验证的语义
  • 您正在构建用于缓存失效的 webhook 或 API 端点