郭佳恩前端工程师
返回首页
15 分钟阅读技术专栏

Next.js 14 Server Actions 实战:告别 API Routes

Server Actions 允许你在服务器端直接运行异步代码。本文演示如何使用 Server Actions 处理表单提交、乐观更新和错误处理,完全替代传统的 API Route 模式。

Next.jsReactServer ActionsFullstack

Server Actions 是 Next.js 14 中最激动人心的特性之一。它让我们不再需要手动创建 API Endpoints 来处理数据变更。

1. 基础表单提交

在 Server Component 中直接定义 Action:

typescript
'use server'

import { revalidatePath } from 'next/cache'
import { db } from '@/lib/db'

export async function createPost(formData: FormData) {
  const title = formData.get('title')
  const content = formData.get('content')

  await db.post.create({
    data: {
      title: title as string,
      content: content as string,
    },
  })

  revalidatePath('/posts')
}

在 Client Component 中使用:

tsx
'use client'

import { createPost } from '@/app/actions'

export function CreatePost() {
  return (
    <form action={createPost}>
      <input type="text" name="title" className="border p-2" />
      <textarea name="content" className="border p-2" />
      <button type="submit">发布</button>
    </form>
  )
}

2. 乐观更新 (Optimistic Updates)

使用 useOptimistic 钩子实现即时反馈。

tsx
'use client'

import { useOptimistic } from 'react'
import { incrementLike } from '@/app/actions'

export function LikeButton({ post }: { post: Post }) {
  const [optimisticLikes, addOptimisticLike] = useOptimistic(
    post.likes,
    (state, newLike: number) => state + newLike
  )

  return (
    <form action={async () => {
      addOptimisticLike(1)
      await incrementLike(post.id)
    }}>
      <button type="submit">
        ❤️ {optimisticLikes}
      </button>
    </form>
  )
}

3. 错误处理与 Pending 状态

使用 useFormStatususeFormState

tsx
'use client'

import { useFormStatus } from 'react-dom'

export function SubmitButton() {
  const { pending } = useFormStatus()
 
  return (
    <button type="submit" disabled={pending}>
      {pending ? '提交中...' : '提交'}
    </button>
  )
}

评论区0

自由讨论你的想法,分享你的实践。

还没有评论

成为第一个发言的人吧