如何控制全路由缓存?(续)
// app/posts/[id]/page.tsx
export async function generateStaticParams() {
const posts = await fetch("https://api.example.com/posts").then((r) =>
r.json()
);
// 预渲染前 50 篇文章
return posts.slice(0, 50).map((post) => ({ id: String(post.id) }));
}
export default async function PostPage({
params,
}: {
params: Promise<{ id: string }>;
}) {
const { id } = await params;
const post = await getPost(id);
return <div>{post.title}</div>;
}
方法 4:use cache 指令(Next.js 15 实验性 / 16 稳定)
// 整个页面声明为可缓存
"use cache";
import { cacheLife } from "next/cache";
export default async function BlogPage() {
cacheLife("hours"); // 缓存 1 小时
const posts = await getPosts();
return <div>...</div>;
}
让页面不被缓存(动态化)
方法 1:使用动态函数
import { cookies } from "next/headers";
export default async function Page() {
await cookies(); // 读取 cookies,页面变成动态的
// ...
}
方法 2:配置 dynamic