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 内置的 数据缓存 来在请求和部署之间持久化结果。
警告:此 API 不稳定,未来可能会发生变化。随着此 API 逐渐稳定,我们将在需要时提供迁移文档和代码修改工具。
参数
const data = unstable_cache(fetchData, keyParts, options)()
fetchData
:这是一个异步函数,用于获取你想要缓存的数据。它必须是一个返回Promise
的函数。keyParts
:这是一个额外的键数组,为缓存提供进一步的标识。默认情况下,unstable_cache
已经使用参数和函数的字符串化版本作为缓存键。在大多数情况下,这是可选的;你只有在使用外部变量而不将它们作为参数传递时才需要使用它。但是,如果你不将闭包作为参数传递,那么在函数内使用的闭包是需要添加的。options
:这是一个控制缓存行为的对象。它可以包含以下属性:tags
:一个标签数组,可用于控制缓存失效。Next.js 不会使用此来唯一标识函数。revalidate
:缓存应该重新验证的秒数。省略或传递false
将无限期缓存或直到调用匹配的revalidateTag()
或revalidatePath()
方法。
返回值
unstable_cache
返回一个函数,当调用时,返回一个解析为缓存数据的 Promise。如果数据不在缓存中,将调用提供的函数,并缓存和返回其结果。
示例
app/page.tsx
TypeScript
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.0 | 引入 unstable_cache 。 |