Sponsor
ntab.devntab.dev 提升效率的新标签页组件
点击查看
Menu

cacheTag

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

使用方法

要使用 cacheTag,需要在你的 next.config.js 文件中启用 dynamicIO 标志

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

cacheTag 函数接受单个字符串值或字符串数组。

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

然后你可以使用 revalidateTag API 在另一个函数中按需清除缓存,例如在路由处理程序服务器操作中:

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

示例

为组件或函数添加标签

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

app/components/bookings.tsx
TypeScript
import { unstable_cacheTag as 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 { unstable_cacheTag as 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')
}