unstable_cache
警告: 此 API 在達到穩定狀態後將由
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);
...
}
須知事項:
- 不支援在快取範圍內存取動態資料來源(如
headers
或cookies
)。若需在快取函式中使用這些資料,請在快取函式外部使用headers
並將所需的動態資料作為參數傳入。- 此 API 使用 Next.js 內建的 資料快取 (Data Cache) 來跨請求和部署保持結果。
參數
const data = unstable_cache(fetchData, keyParts, options)()
fetchData
: 這是一個非同步函式,用於獲取您想要快取的資料。它必須是一個回傳Promise
的函式。keyParts
: 這是一個額外的鍵值陣列,用於進一步識別快取。預設情況下,unstable_cache
已經使用參數和函式的字串化版本作為快取鍵。在大多數情況下是可選的;唯一需要使用的時機是當您使用外部變數但未將其作為參數傳遞時。然而,若未將閉包作為參數傳遞,則務必將函式內使用的閉包加入其中。options
: 這是一個控制快取行為的物件。它可以包含以下屬性:tags
: 可用於控制快取失效的標籤陣列。Next.js 不會使用此屬性來唯一識別函式。revalidate
: 快取應重新驗證的秒數。省略或傳遞false
可無限期快取,直到呼叫匹配的revalidateTag()
或revalidatePath()
方法。
回傳值
unstable_cache
回傳一個函式,當呼叫時會回傳一個解析為快取資料的 Promise。若資料不在快取中,則會呼叫提供的函式,並將其結果快取後回傳。
範例
import { unstable_cache } from 'next/cache'
export default async function Page({
params,
}: {
params: Promise<{ userId: string }>
}) {
const { userId } = await params
const getCachedUser = unstable_cache(
async () => {
return { id: userId }
},
[userId], // 將使用者 ID 加入快取鍵
{
tags: ['users'],
revalidate: 60,
}
)
//...
}
import { unstable_cache } from 'next/cache';
export default async function Page({ params } }) {
const { userId } = await params
const getCachedUser = unstable_cache(
async () => {
return { id: userId };
},
[userId], // 將使用者 ID 加入快取鍵
{
tags: ["users"],
revalidate: 60,
}
);
//...
}
版本歷史
版本 | 變更內容 |
---|---|
v14.0.0 | 首次引入 unstable_cache 。 |