Server Actions 理论与实践

Server Actions 是 React 19 最重要的新特性之一,允许客户端组件直接调用服务端函数,无需手动创建 API 路由。

基础使用

// app/actions.ts
"use server";
import { db } from "@/lib/db";
import { revalidatePath } from "next/cache";

export async function createPost(formData: FormData) {
  const title = formData.get("title");
  const content = formData.get("content");
  const post = await db.post.create({ data: { title, content } });
  revalidatePath("/posts");
  return post;
}

在客户端组件中使用:

"use client";
import { useTransition } from "react";
import { createPost } from "./actions";

export function PostForm() {
  const [pending, startTransition] = useTransition();
  return (
    <form action={createPost}>
      <input name="title" required />
      <textarea name="content" />
      <button type="submit" disabled={pending}>发布</button>
    </form>
  );
}

Server Actions 配合 revalidatePath 可以实现 mutations 后自动刷新页面数据,配合 useOptimistic 可以实现乐观更新,无需手动管理 loading 状态。