前言
目前博客已经支持动态页面重部署,简单来说就是写完文章发布后,不用再去Redeploy了,直接就能在访问的时候完成构建,并且保留构建成果作为缓存。
从这个角度来说,现在的RTheme才是个比较理想的动态站,至少写文章变的简单多了——现在只需要编辑、保存,即可。
实际上算是比较简单的,只是用了Nextjs 14里面的新机制Server Action,允许你在服务器端执行代码,并直接调用它来重新验证页面缓存。
实现
非常简单,例如:
// app/api/_utils/actions.ts
'use server';
import { revalidatePath } from 'next/cache';
export async function refreshPosts() {
revalidatePath('/posts'); // 重新渲染 `/posts` 页面
revalidatePath('/posts/[name]'); // 重新渲染所有`/posts/xxx`页面
}
// 文章编辑/修改api
import { NextResponse } from 'next/server';
import prisma from '@/app/api/_utils/prisma';
import { refreshPosts } from '@/app/api/_utils/actions';
export async function POST(req: Request) {
try {
const data = await req.json();
const post = await prisma.post.create({
data: {
title: data.title,
name: data.name,
published: true,
createdAt: new Date(),
},
});
// 文章添加成功后,刷新博客页面
await refreshPosts();
return NextResponse.json({ success: true, post });
} catch (error) {
return NextResponse.json({ success: false, error: error.message }, { status: 500 });
}
}
实际上如果你的其余文章内容与修改无关的话,你可以自己让调用Server Actions的组件自己传参来刷新特定页面而非所有博客,毕竟如果真全刷新了回到无缓存状态,那么第一次加载的速度还是非常慢的。
同理,只要是个page.tsx
就都能通过Server Actions进行刷新,也包括RSS
和Sitemap
。