cacheLife 选项允许您在使用 cacheLife 函数时,在组件或函数内部以及 use cache 指令 的作用域内,定义自定义缓存配置文件。
要定义配置文件,请启用 cacheComponents 标志,并在 next.config.js 文件中的 cacheLife 对象中添加缓存配置文件。例如,一个 blog 配置文件:
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
cacheComponents: true,
cacheLife: {
blog: {
stale: 3600, // 1 hour
revalidate: 900, // 15 minutes
expire: 86400, // 1 day
},
},
}
export default nextConfigmodule.exports = {
cacheComponents: true,
cacheLife: {
blog: {
stale: 3600, // 1 hour
revalidate: 900, // 15 minutes
expire: 86400, // 1 day
},
},
}您现在可以在您的组件或函数中按如下方式使用此自定义 blog 配置:
import { cacheLife } from 'next/cache'
export async function getCachedData() {
'use cache'
cacheLife('blog')
const data = await fetch('/api/data')
return data
}import { cacheLife } from 'next/cache'
export async function getCachedData() {
'use cache'
cacheLife('blog')
const data = await fetch('/api/data')
return data
}配置对象具有以下格式的键值:
| Property | Value | 描述 | 要求 |
|---|---|---|---|
stale | number | 客户端在不检查服务器的情况下应该缓存值的持续时间。 | 可选 |
revalidate | number | 缓存应该在服务器上刷新的频率;在重新验证时,可能会提供旧值。 | 可选 |
expire | number | 值在切换到动态之前可以保持陈旧的最大持续时间。 | 可选 - 必须长于 revalidate |