updateTag 允许您在 Server Actions 中,根据需要更新特定缓存标签的 缓存数据。
此函数专为读取自己写入的数据 (read-your-own-writes) 场景设计,即用户进行更改(例如创建帖子)后,用户界面会立即显示该更改,而不是过时的数据。
updateTag 只能在 Server Actions 中调用。它不能在 Route Handlers、Client Components 或任何其他上下文中使用。
如果您需要在 Route Handlers 或其他上下文中使缓存标签失效,请改用 revalidateTag。
须知:
updateTag会立即使指定标签的缓存数据过期。下一个请求将等待获取最新数据,而不是从缓存中提供过时内容,从而确保用户立即看到他们的更改。
updateTag(tag: string): void;tag:一个字符串,表示与您要更新的数据关联的缓存标签。长度不能超过 256 个字符。此值区分大小写。标签必须首先分配给缓存数据。您可以通过两种方式完成此操作:
fetch 的 next.tags 选项来缓存外部 API 请求:fetch(url, { next: { tags: ['posts'] } })'use cache' 指令的缓存函数或组件内部使用 cacheTag:import { cacheTag } from 'next/cache'
async function getData() {
'use cache'
cacheTag('posts')
// ...
}updateTag 不返回任何值。
尽管 updateTag 和 revalidateTag 都使缓存数据失效,但它们服务于不同的目的:
updateTag:
revalidateTag:
profile="max"(推荐):在后台获取最新数据时提供缓存数据(stale-while-revalidate,即陈旧时重新验证)updateTag'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}`)
}'use server'
import { updateTag } from 'next/cache'
import { redirect } from 'next/navigation'
export async function createPost(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}`)
}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:
在以下情况改用 revalidateTag:
revalidateTag - 用于在 Route Handlers 中使标签失效revalidatePath - 用于使特定路径失效