NNext.js 中文网 GitHub

cacheLife

了解如何在 Next.js 中设置 cacheLife 配置。

通过 cacheLife 选项,你可以在组件或函数中使用 cacheLife 函数时定义自定义缓存配置,并在 use cache 指令的作用域内使用。

用法#

要定义配置,请启用 cacheComponents 标志,并在 next.config.js 文件的 cacheLife 对象中添加缓存配置。例如,一个 blog 配置:

next.config.ts
import type { NextConfig } from 'next'

const nextConfig: NextConfig = {
  cacheComponents: true,
  cacheLife: {
    blog: {
      stale: 3600, // 1 小时
      revalidate: 900, // 15 分钟
      expire: 86400, // 1 天
    },
  },
}

export default nextConfig
next.config.js
module.exports = {
  cacheComponents: true,
  cacheLife: {
    blog: {
      stale: 3600, // 1 小时
      revalidate: 900, // 15 分钟
      expire: 86400, // 1 天
    },
  },
}

现在你可以在组件或函数中使用这个自定义的 blog 配置,如下所示:

app/actions.ts
import { cacheLife } from 'next/cache'

export async function getCachedData() {
  'use cache'
  cacheLife('blog')
  const res = await fetch('https://api.example.com/data')
  const data = await res.json()
  return data
}
app/actions.js
import { cacheLife } from 'next/cache'

export async function getCachedData() {
  'use cache'
  cacheLife('blog')
  const res = await fetch('https://api.example.com/data')
  const data = await res.json()
  return data
}

你也可以通过定义同名配置来覆盖内置配置(default、seconds、minutes、hours、days、weeks 或 max)。请参阅覆盖默认缓存配置。

参考#

配置对象包含具有以下格式的键值:

属性值说明要求
stalenumber客户端在不向服务器确认的情况下缓存某个值的时长。可选
revalidatenumber缓存在服务器上刷新的频率;重新验证期间可能会提供过期值。可选
expirenumber某个值在切换为动态之前可以保持过期状态的最长时长。可选 - 必须长于 revalidate

版本历史#

版本变更
v16.0.0cacheLife 已稳定,并从 experimental.cacheLife 移至顶层 cacheLife 选项。
Next.js 中文网