cacheTag

cacheTag 函式允許你為快取資料加上標籤,以便按需使其失效。透過將標籤與快取項目關聯,你可以選擇性地清除或重新驗證特定快取項目,而不影響其他快取資料。

使用方法

要使用 cacheTag,請先在 next.config.js 檔案中啟用 dynamicIO 標記

import type { NextConfig } from 'next'

const nextConfig: NextConfig = {
  experimental: {
    dynamicIO: true,
  },
}

export default nextConfig

cacheTag 函式接受單一字串值或字串陣列。

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 在另一個函式中按需清除快取,例如在 路由處理程式伺服器動作 (Server Action) 中:

'use server'

import { revalidateTag } from 'next/cache'

export default async function submit() {
  await addPost()
  revalidateTag('my-data')
}

注意事項

  • 冪等標籤:多次套用相同標籤不會產生額外效果。
  • 多重標籤:你可以透過傳遞陣列給 cacheTag,為單一快取項目分配多個標籤。
cacheTag('tag-one', 'tag-two')

範例

為元件或函式加上標籤

在快取函式或元件中呼叫 cacheTag 來為快取資料加上標籤:

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 //...
}

從外部資料建立標籤

你可以使用非同步函式回傳的資料來為快取項目加上標籤。

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,你可以在需要時使特定標籤的快取失效:

'use server'

import { revalidateTag } from 'next/cache'

export async function updateBookings() {
  await updateBookingData()
  revalidateTag('bookings-data')
}

On this page