首页/ AI 技能 / @skilllib/skill-2117939930272412443
Skill站外收录 @skilllib/skill-2117939930272412443

server-actions

提供在 Next.js 应用中直接执行服务端逻辑的能力,支持表单提交、数据变更与远程过程调用,无需额外搭建 API 路由,兼顾渐进增强与服务端验证,并内置路径重验证和状态反馈机制。

0.0 (0) 30 次安装 原作者 编程导航
收录于 2026-01-22
效率工具 AI 技能

Skills.MD

# Server Actions ## **Priority: P1 (HIGH)** Handle form submissions and mutations without creating API endpoints. ## Implementation - **Directive**: Add `'use server'` at the top of an async function. - **Usage**: Pass to `action` prop of `<form>` or invoke from event handlers. ```tsx // actions.ts 'use server'; export async function createPost(formData: FormData) { const title = formData.get('title'); await db.post.create({ title }); revalidatePath('/posts'); // Refresh UI } ``` ## Client Invocation - **Form**: `<form action={createPost}>` (Progressive enhancements work without JS). - **Event Handler**: `onClick={() => createPost(data)}`. - **Pending State**: Use `useFormStatus` hook (must be inside a component rendered within the form). ## Validation & Error Handling - **Zod**: Always validate `FormData` or arguments on the server. - **Return Values**: Return serializable objects `{ success: boolean, error?: string }` to handle feedback on Client. ## Security - **Authentication**: Check `auth()` (e.g., NextAuth) session inside every Server Action. - **Closure**: Be careful with closures in Server Actions defined inside Components (they capture context encrypted). Prefer defining actions in separate files (`actions.ts`).

评论 0

还没有评论,来抢沙发。