跳到內容
API 參考函式unstable_cache

unstable_cache

注意: 這個 API 將在 use cache 達到穩定狀態時,被 use cache 取代。

unstable_cache 允許您快取昂貴操作(例如資料庫查詢)的結果,並在多個請求中重複使用它們。

import { getUser } from './data';
import { unstable_cache } from 'next/cache';
 
const getCachedUser = unstable_cache(
  async (id) => getUser(id),
  ['my-app-user']
);
 
export default async function Component({ userID }) {
  const user = await getCachedUser(userID);
  ...
}

要知道的好處:

  • 不支援在快取範圍內存取動態資料來源,例如 headerscookies。如果您需要在快取函式中使用此資料,請在快取函式外部使用 headers,並將所需的動態資料作為引數傳遞進來。
  • 此 API 使用 Next.js 的內建資料快取,以在請求和部署之間持久保存結果。

警告:此 API 不穩定,未來可能會變更。如果需要,我們將在此 API 穩定後提供遷移文件和 codemod。

參數

const data = unstable_cache(fetchData, keyParts, options)()
  • fetchData:這是一個非同步函式,用於抓取您要快取的資料。它必須是一個回傳 Promise 的函式。
  • keyParts:這是一個額外的鍵陣列,可進一步為快取新增識別。預設情況下,unstable_cache 已經使用引數和函式的字串化版本作為快取鍵。在大多數情況下,它是選用的;唯一需要使用它的時機是當您使用外部變數而沒有將它們作為參數傳遞時。但是,如果您不將閉包作為參數傳遞,則新增函式內使用的閉包非常重要。
  • options:這是一個物件,用於控制快取的行為。它可以包含以下屬性
    • tags:標籤陣列,可用於控制快取失效。Next.js 不會使用它來唯一識別函式。
    • revalidate:快取應重新驗證的秒數。省略或傳遞 false 以無限期快取,或直到呼叫相符的 revalidateTag()revalidatePath() 方法。

回傳值

unstable_cache 回傳一個函式,當被調用時,會回傳一個 Promise,該 Promise 解析為快取的資料。如果資料不在快取中,將調用提供的函式,並且其結果將被快取並回傳。

範例

app/page.tsx
import { unstable_cache } from 'next/cache'
 
export default async function Page({
  params,
}: {
  params: Promise<{ userId: string }>
}) {
  const userId = (await params).userId
  const getCachedUser = unstable_cache(
    async () => {
      return { id: userId }
    },
    [userId], // add the user ID to the cache key
    {
      tags: ['users'],
      revalidate: 60,
    }
  )
 
  //...
}

版本歷史

版本變更
v14.0.0unstable_cache 引入。