Menu

如何更新数据

在 Next.js 中,你可以使用 React 的 Server Functions 更新数据。本页将介绍如何创建调用 Server Functions。

创建 Server Functions

可以通过使用 use server 指令来定义 Server Function。你可以将该指令放在异步函数的顶部,将该函数标记为 Server Function,或者放在单独文件的顶部,将该文件的所有导出标记为 Server Function。在大多数情况下,我们建议使用单独的文件。

app/lib/actions.ts
TypeScript
'use server'
 
export async function createPost(formData: FormData) {}
 
export async function deletePost(formData: FormData) {}

Server Components

Server Functions 可以通过在函数体顶部添加 "use server" 指令来内联到 Server Components 中:

app/page.tsx
TypeScript
export default function Page() {
  // Server Action
  async function createPost() {
    'use server'
    // Update data
    // ...
 
  return <></>
}

Client Components

在 Client Components 中无法定义 Server Functions。但是,你可以通过从顶部有 "use server" 指令的文件中导入来在 Client Components 中调用它们:

app/actions.ts
TypeScript
'use server'
 
export async function createPost() {}
app/ui/button.tsx
TypeScript
'use client'
 
import { createPost } from '@/app/actions'
 
export function Button() {
  return <button formAction={createPost}>Create</button>
}

调用 Server Functions

调用 Server Function 主要有两种方式:

  1. Server 和 Client Components 中的表单
  2. Client Components 中的事件处理程序

表单

React 扩展了 HTML <form> 元素,允许通过 HTML action 属性调用 Server Function。

在表单中调用时,函数会自动接收 FormData 对象。你可以使用原生 FormData 方法来提取数据:

app/ui/form.tsx
TypeScript
import { createPost } from '@/app/actions'
 
export function Form() {
  return (
    <form action={createPost}>
      <input type="text" name="title" />
      <input type="text" name="content" />
      <button type="submit">Create</button>
    </form>
  )
}
app/actions.ts
TypeScript
'use server'
 
export async function createPost(formData: FormData) {
  const title = formData.get('title')
  const content = formData.get('content')
 
  // Update data
  // Revalidate cache
}

**值得注意的是:**当传递给 action 属性时,Server Functions 也被称为 Server Actions

事件处理程序

你可以通过使用 onClick 等事件处理程序在 Client Component 中调用 Server Function。

app/like-button.tsx
TypeScript
'use client'
 
import { incrementLike } from './actions'
import { useState } from 'react'
 
export default function LikeButton({ initialLikes }: { initialLikes: number }) {
  const [likes, setLikes] = useState(initialLikes)
 
  return (
    <>
      <p>Total Likes: {likes}</p>
      <button
        onClick={async () => {
          const updatedLikes = await incrementLike()
          setLikes(updatedLikes)
        }}
      >
        Like
      </button>
    </>
  )
}

显示等待状态

在执行 Server Function 时,你可以使用 React 的 useActionState 钩子显示加载指示器。这个钩子返回一个 pending 布尔值:

app/ui/button.tsx
TypeScript
'use client'
 
import { useActionState } from 'react'
import { createPost } from '@/app/actions'
import { LoadingSpinner } from '@/app/ui/loading-spinner'
 
export function Button() {
  const [state, action, pending] = useActionState(createPost, false)
 
  return (
    <button onClick={async () => action()}>
      {pending ? <LoadingSpinner /> : 'Create Post'}
    </button>
  )
}

重新验证缓存

执行更新后,你可以通过在 Server Function 中调用 revalidatePathrevalidateTag 来重新验证 Next.js 缓存并显示更新后的数据:

app/lib/actions.ts
TypeScript
'use server'
 
import { revalidatePath } from 'next/cache'
 
export async function createPost(formData: FormData) {
  // Update data
  // ...
 
  revalidatePath('/posts')
}

重定向

在执行更新后,你可能想要将用户重定向到另一个页面。你可以通过在 Server Function 中调用 redirect 来实现:

app/lib/actions.ts
TypeScript
'use server'
 
import { redirect } from 'next/navigation'
 
export async function createPost(formData: FormData) {
  // Update data
  // ...
 
  redirect('/posts')
}