警告: 此 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 内置的 数据缓存 来在跨请求和部署时持久化结果。
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], // add the user ID to the cache key
{
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], // add the user ID to the cache key
{
tags: ["users"],
revalidate: 60,
}
);
//...
}| 版本 | 更改 |
|---|---|
v14.0.0 | unstable_cache 引入。 |