cacheTag
cacheTag
函数允许你为缓存数据添加标签以进行按需失效。通过将标签与缓存条目关联,你可以选择性地清除或重新验证缓存的特定部分,而不会影响其他缓存数据。
使用方法
要使用 cacheTag
,需要在你的 next.config.js
中启用 dynamicIO
标志,并从 next/cache
中导入 cacheTag
:
next.config.ts
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
experimental: {
dynamicIO: true,
},
}
export default nextConfig
app/actions.ts
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
结合使用
将 cacheTag
与 revalidateTag
结合使用,可以按需清除带标签的缓存条目。这在数据更新后或外部事件触发时更新数据的场景下非常有用。
app/submit.ts
'use server'
import { revalidateTag } from 'next/cache'
export default async function submit() {
await addPost()
revalidateTag('my-data')
}
示例
为缓存数据添加标签
通过在缓存函数或组件中调用 cacheTag
来为你的缓存数据添加标签:
app/components/bookings.tsx
import {
unstable_cacheTag as cacheTag,
unstable_cacheLife as cacheLife,
} from 'next/cache'
interface BookingsProps {
type: string
}
export async function Bookings({ type = 'massage' }: BookingsProps) {
'use cache'
cacheLife('minutes')
cacheTag('bookings-data')
async function getBookingsData() {
const data = await fetch(`/api/bookings?type=${encodeURIComponent(type)}`)
return data
}
return //...
}
使用数据添加标签
你可以使用异步函数返回的数据为缓存条目添加标签。
app/components/bookings.tsx
import {
unstable_cacheTag as cacheTag,
unstable_cacheLife as cacheLife,
} from 'next/cache'
interface BookingsProps {
type: string
}
export async function Bookings({ type = 'massage' }: BookingsProps) {
async function getBookingsData() {
'use cache'
cacheLife('minutes')
const data = await fetch(`/api/bookings?type=${encodeURIComponent(type)}`)
cacheTag('bookings-data', data.id)
return data
}
return //...
}
使带标签的缓存失效
在需要时使特定标签的缓存失效:
app/actions.ts
'use server'
import { revalidateTag } from 'next/cache'
export async function updateBookings() {
await updateBookingData()
revalidateTag('bookings-data')
}
注意事项
- 幂等标签:多次应用相同的标签不会产生额外效果。
- 多个标签:你可以通过向
cacheTag
传递数组来为单个缓存条目分配多个标签。
cacheTag(['tag-one', 'tag-two'])