'use cache: private' 指令的工作方式与 use cache 类似,但允许你使用像 cookies、headers 或 search params 这样的运行时 API。
须知: 与
use cache不同,私有缓存不会被静态预渲染,因为它们包含不应在用户之间共享的个性化数据。
要使用 'use cache: private',请在你的 next.config.ts 文件中启用 cacheComponents 标志:
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
cacheComponents: true,
};
export default nextConfig;/** @type {import('next').NextConfig} */
const nextConfig = {
cacheComponents: true,
};
export default nextConfig;然后,将 'use cache: private' 添加到你的函数中,并附带一个 cacheLife 配置。
import { Suspense } from "react";
import { cookies } from "next/headers";
import { cacheLife, cacheTag } from "next/cache";
export default async function ProductPage({
params,
}: {
params: Promise<{ id: string }>;
}) {
const { id } = await params;
return (
<div>
<ProductDetails id={id} />
<Suspense fallback={<div>Loading recommendations...</div>}>
<Recommendations productId={id} />
</Suspense>
</div>
);
}
async function Recommendations({ productId }: { productId: string }) {
const recommendations = await getRecommendations(productId);
return (
<div>
{recommendations.map((rec) => (
<ProductCard key={rec.id} product={rec} />
))}
</div>
);
}
async function getRecommendations(productId: string) {
"use cache: private";
cacheTag(`recommendations-${productId}`);
cacheLife({ stale: 60 }); // Minimum 30 seconds required for runtime prefetch
// Access cookies within private cache functions
const sessionId = (await cookies()).get("session-id")?.value || "guest";
return getPersonalizedRecommendations(productId, sessionId);
}import { Suspense } from "react";
import { cookies } from "next/headers";
import { cacheLife, cacheTag } from "next/cache";
export default async function ProductPage({ params }) {
const { id } = await params;
return (
<div>
<ProductDetails id={id} />
<Suspense fallback={<div>Loading recommendations...</div>}>
<Recommendations productId={id} />
</Suspense>
</div>
);
}
async function Recommendations({ productId }) {
const recommendations = await getRecommendations(productId);
return (
<div>
{recommendations.map((rec) => (
<ProductCard key={rec.id} product={rec} />
))}
</div>
);
}
async function getRecommendations(productId) {
"use cache: private";
cacheTag(`recommendations-${productId}`);
cacheLife({ stale: 60 }); // Minimum 30 seconds required for runtime prefetch
// Access cookies within private cache functions
const sessionId = (await cookies()).get("session-id")?.value || "guest";
return getPersonalizedRecommendations(productId, sessionId);
}以下请求特定的 API 可用于 'use cache: private' 函数中:
| API | 在 use cache 中允许 | 在 'use cache: private' 中允许 |
|---|---|---|
cookies() | 否 | 是 |
headers() | 否 | 是 |
searchParams | 否 | 是 |
connection() | 否 | 否 |
注意:
connection()API 在use cache和'use cache: private'中均被禁止,因为它提供了无法安全缓存的连接特定信息。
| 版本 | 更改 |
|---|---|
v16.0.0 | "use cache: private" 通过缓存组件功能启用。 |