Menu

cacheTag

cacheTag 函数允许你为缓存数据添加标签,以便按需失效。通过将标签与缓存条目关联,你可以选择性地清除或重新验证特定的缓存条目,而不会影响其他缓存数据。

用法

要使用 cacheTag,请在 next.config.js 文件中启用 cacheComponents 标志

next.config.ts
TypeScript
import type { NextConfig } from 'next'
 
const nextConfig: NextConfig = {
  cacheComponents: true,
}
 
export default nextConfig

cacheTag 函数接受一个或多个字符串值。

app/data.ts
TypeScript
import { cacheTag } from 'next/cache'
 
export async function getData() {
  'use cache'
  cacheTag('my-data')
  const data = await fetch('/api/data')
  return data
}

然后,你可以在另一个函数中使用 revalidateTag API 按需清除缓存,例如在 route handlerServer Action 中:

app/action.ts
TypeScript
'use server'
 
import { revalidateTag } from 'next/cache'
 
export default async function submit() {
  await addPost()
  revalidateTag('my-data')
}

值得注意的是

  • 幂等标签:多次应用相同的标签不会产生额外效果。
  • 多个标签:你可以通过向 cacheTag 传递多个字符串值,为单个缓存条目分配多个标签。
cacheTag('tag-one', 'tag-two')
  • 限制:自定义标签的最大长度为 256 个字符,最大标签数量为 128 个。

示例

为组件或函数添加标签

通过在缓存的函数或组件中调用 cacheTag 来为缓存数据添加标签:

app/components/bookings.tsx
TypeScript
import { cacheTag } from 'next/cache'
 
interface BookingsProps {
  type: string
}
 
export async function Bookings({ type = 'haircut' }: BookingsProps) {
  'use cache'
  cacheTag('bookings-data')
 
  async function getBookingsData() {
    const data = await fetch(`/api/bookings?type=${encodeURIComponent(type)}`)
    return data
  }
 
  return //...
}

从外部数据创建标签

你可以使用异步函数返回的数据来为缓存条目添加标签。

app/components/bookings.tsx
TypeScript
import { cacheTag } from 'next/cache'
 
interface BookingsProps {
  type: string
}
 
export async function Bookings({ type = 'haircut' }: BookingsProps) {
  async function getBookingsData() {
    'use cache'
    const data = await fetch(`/api/bookings?type=${encodeURIComponent(type)}`)
    cacheTag('bookings-data', data.id)
    return data
  }
  return //...
}

使已标记的缓存失效

使用 revalidateTag,你可以在需要时使特定标签的缓存失效:

app/actions.ts
TypeScript
'use server'
 
import { revalidateTag } from 'next/cache'
 
export async function updateBookings() {
  await updateBookingData()
  revalidateTag('bookings-data')
}