unstable_cache
unstable_cache 函数的 API 参考。
注意:
在大多数用例中,
use cache在 Next.js 16 中取代了此 API。我们建议启用 Cache Components 并迁移到use cache指令。对于必须在部署之间持久保存的非
fetch数据,请继续使用unstable_cache。来自use cache和use cache: remote的缓存条目不会延续到新的部署,因为它们的缓存键包含 build ID 或deploymentId。
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。请在缓存函数之外读取数据,并将所需的值作为参数传入。- 此 API 使用 Next.js 内置缓存来跨请求和部署持久保存结果。请参阅缓存与重新验证。
不支持的操作
传给 unstable_cache 的函数不能依赖于传入的请求。请在调用缓存函数之前从 cookies() 或 headers() 读取值,然后将这些值作为参数传入,使其成为缓存键的一部分。
缓存函数还不能:
- 调用
connection(),因为它需要传入的请求 - 启用或禁用草稿模式
- 在缓存执行期间调用
revalidateTag()、updateTag()或revalidatePath() - 调用使用
use cache: private指令的函数
在调用缓存函数之前执行依赖于请求的工作。之后在服务器操作或路由处理器中执行变更和重新验证。
参数
const data = unstable_cache(fetchData, keyParts, options)()
fetchData:这是一个异步函数,用于获取你想缓存的数据。它必须是一个返回Promise的函数。keyParts:这是一个额外的键数组,用于进一步标识缓存。默认情况下,unstable_cache已经将参数以及函数的字符串化版本用作缓存键。它在大多数情况下是可选的;唯一需要使用它的场景是,你使用了外部变量却没有将它们作为参数传入。不过,如果函数内部使用了闭包却没有将其作为参数传入,那么务必将其添加进来。options:这是一个控制缓存行为的对象。它可以包含以下属性:tags:一个标签数组,可用于控制缓存失效。Next.js 不会用它来唯一标识该函数。revalidate:缓存应在多少秒后重新验证。省略或传入false可无限期缓存,直到调用匹配的revalidateTag()或revalidatePath()方法为止。
返回值
unstable_cache 返回一个函数,调用该函数时会返回一个 Promise,其解析结果为缓存的数据。如果缓存中没有该数据,则会调用传入的函数,并将其结果缓存后返回。
示例
TypeScript
app/page.tsxtsx
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,
}
)
//...
}
JavaScript
app/page.jsxjsx
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。 |