修改数据
了解如何在 Next.js 中使用 Server Functions 和 Server Actions 修改数据。
你可以在 Next.js 中使用 React Server Functions 来修改数据。本页将介绍如何创建和调用 Server Functions。有关 Next.js 特有的行为(单次往返响应、顺序分发、安全性、部署),请参阅 Server Actions 与数据修改。
什么是 Server Functions?#
Server Function 是在服务器上运行的异步函数。你可以通过网络请求从客户端调用它们,这就是为什么它们必须是异步的。
在 action 或修改数据的上下文中,它们也被称为 Server Actions。
按照惯例,Server Action 是与 startTransition 一起使用的异步函数。当函数出现以下情况时,这会自动发生:
- 通过
action属性传递给<form>。 - 通过
formAction属性传递给<button>。
当调用 action 时,Next.js 可以在单次服务器往返中返回更新后的 UI 和新数据。
在幕后,action 使用 POST 方法,并且只有这种 HTTP 方法才能调用它们。
[!WARNING] Server Functions 可通过直接的 POST 请求访问,而不仅仅是通过应用的 UI。务必在每个 Server Function 内部验证身份验证和授权。有关推荐的模式,请参阅数据安全指南。
小知识: Server Action 是以特定方式(用于处理表单提交和数据修改)使用的 Server Function。Server Function 是更宽泛的术语。
创建 Server Functions#
可以使用 use server 指令来定义 Server Function。你可以将该指令放在异步函数的顶部以将该函数标记为 Server Function,或者放在单独文件的顶部以将该文件的所有导出都标记为 Server Function。
import { auth } from '@/lib/auth'
export async function createPost(formData: FormData) {
'use server'
const session = await auth()
if (!session?.user) {
throw new Error('Unauthorized')
}
const title = formData.get('title')
const content = formData.get('content')
// 修改数据
// 重新验证缓存
}
export async function deletePost(formData: FormData) {
'use server'
const session = await auth()
if (!session?.user) {
throw new Error('Unauthorized')
}
const id = formData.get('id')
// 在删除前验证用户是否拥有此资源
// 修改数据
// 重新验证缓存
}import { auth } from '@/lib/auth'
export async function createPost(formData) {
'use server'
const session = await auth()
if (!session?.user) {
throw new Error('Unauthorized')
}
const title = formData.get('title')
const content = formData.get('content')
// 修改数据
// 重新验证缓存
}
export async function deletePost(formData) {
'use server'
const session = await auth()
if (!session?.user) {
throw new Error('Unauthorized')
}
const id = formData.get('id')
// 在删除前验证用户是否拥有此资源
// 修改数据
// 重新验证缓存
}Server Components#
可以通过在函数体顶部添加 "use server" 指令,将 Server Functions 内联到 Server Components 中:
export default function Page() {
// Server Action
async function createPost(formData: FormData) {
'use server'
// ...
}
return <></>
}export default function Page() {
// Server Action
async function createPost(formData) {
'use server'
// ...
}
return <></>
}小知识: Server Components 默认支持渐进增强,这意味着即使 JavaScript 尚未加载或被禁用,调用 Server Actions 的表单也会被提交。
Client Components#
无法在 Client Components 中定义 Server Functions。不过,你可以通过从顶部带有 "use server" 指令的文件中导入它们,从而在 Client Components 中调用它们:
'use server'
export async function createPost() {}'use server'
export async function createPost() {}'use client'
import { createPost } from '@/app/actions'
export function Button() {
return <button formAction={createPost}>Create</button>
}'use client'
import { createPost } from '@/app/actions'
export function Button() {
return <button formAction={createPost}>Create</button>
}小知识: 在 Client Components 中,如果 JavaScript 尚未加载,调用 Server Actions 的表单会将提交排队,并会优先进行 hydration。hydration 之后,表单提交时浏览器不会刷新。
将 action 作为 props 传递#
你还可以将 action 作为 prop 传递给 Client Component:
<ClientComponent updateItemAction={updateItem} />'use client'
export default function ClientComponent({
updateItemAction,
}: {
updateItemAction: (formData: FormData) => void
}) {
return <form action={updateItemAction}></form>
}'use client'
export default function ClientComponent({ updateItemAction }) {
return <form action={updateItemAction}></form>
}调用 Server Functions#
调用 Server Function 主要有两种方式:
小知识: Server Functions 专用于服务器端的数据修改。客户端一次只分发并等待一个调用。请参阅客户端的顺序分发。如果你需要并行获取数据,请在 Server Components 中使用数据获取,或在单个 Server Function 或 Route Handler 中执行并行工作。
表单#
React 扩展了 HTML <form> 元素,允许通过 HTML action 属性调用 Server Function。
在表单中调用时,该函数会自动接收 FormData 对象。你可以使用原生 FormData 方法来提取数据:
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>
)
}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>
)
}'use server'
import { auth } from '@/lib/auth'
export async function createPost(formData: FormData) {
const session = await auth()
if (!session?.user) {
throw new Error('Unauthorized')
}
const title = formData.get('title')
const content = formData.get('content')
// 修改数据
// 重新验证缓存
}'use server'
import { auth } from '@/lib/auth'
export async function createPost(formData) {
const session = await auth()
if (!session?.user) {
throw new Error('Unauthorized')
}
const title = formData.get('title')
const content = formData.get('content')
// 修改数据
// 重新验证缓存
}事件处理程序#
你可以在 Client Component 中使用 onClick 等事件处理程序来调用 Server Function。
'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>
</>
)
}'use client'
import { incrementLike } from './actions'
import { useState } from 'react'
export default function LikeButton({ initialLikes }) {
const [likes, setLikes] = useState(initialLikes)
return (
<>
<p>Total Likes: {likes}</p>
<button
onClick={async () => {
const updatedLikes = await incrementLike()
setLikes(updatedLikes)
}}
>
Like
</button>
</>
)
}示例#
显示 pending 状态#
在执行 Server Function 时,你可以使用 React 的 useActionState hook 显示加载指示器。这个 hook 返回一个 pending 布尔值:
'use client'
import { useActionState, startTransition } 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={() => startTransition(action)}>
{pending ? <LoadingSpinner /> : 'Create Post'}
</button>
)
}'use client'
import { useActionState, startTransition } 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={() => startTransition(action)}>
{pending ? <LoadingSpinner /> : 'Create Post'}
</button>
)
}请参阅构建交互式应用指南,深入了解响应式交互,包括 pending 反馈、乐观 UI、transitions 和错误处理。
小知识:启用 experimental
useOffline配置后,因连接中断而中断的 Server Action 会保持 pending 状态,并在网络恢复时完成。
刷新数据#
数据修改后,你可能希望刷新当前页面以显示最新数据。你可以在 Server Action 中从 next/cache 调用 refresh 来实现:
'use server'
import { auth } from '@/lib/auth'
import { refresh } from 'next/cache'
export async function updatePost(formData: FormData) {
const session = await auth()
if (!session?.user) {
throw new Error('Unauthorized')
}
// 修改数据
// ...
refresh()
}'use server'
import { auth } from '@/lib/auth'
import { refresh } from 'next/cache'
export async function updatePost(formData) {
const session = await auth()
if (!session?.user) {
throw new Error('Unauthorized')
}
// 修改数据
// ...
refresh()
}这会刷新客户端路由器,确保 UI 反映最新状态。refresh() 函数不会重新验证带标签的数据。要重新验证带标签的数据,请改用 updateTag 或 revalidateTag。
重新验证数据#
执行数据修改后,你可以在 Server Function 中调用 revalidatePath 或 revalidateTag 来重新验证 Next.js 缓存并显示更新后的数据:
import { auth } from '@/lib/auth'
import { revalidatePath } from 'next/cache'
export async function createPost(formData: FormData) {
'use server'
const session = await auth()
if (!session?.user) {
throw new Error('Unauthorized')
}
// 修改数据
// ...
revalidatePath('/posts')
}import { auth } from '@/lib/auth'
import { revalidatePath } from 'next/cache'
export async function createPost(formData) {
'use server'
const session = await auth()
if (!session?.user) {
throw new Error('Unauthorized')
}
// 修改数据
// ...
revalidatePath('/posts')
}数据修改后重定向#
你可能希望在数据修改后将用户重定向到其他页面。你可以在 Server Function 中调用 redirect 来实现。
'use server'
import { auth } from '@/lib/auth'
import { revalidatePath } from 'next/cache'
import { redirect } from 'next/navigation'
export async function createPost(formData: FormData) {
const session = await auth()
if (!session?.user) {
throw new Error('Unauthorized')
}
// 修改数据
// ...
revalidatePath('/posts')
redirect('/posts')
}'use server'
import { auth } from '@/lib/auth'
import { revalidatePath } from 'next/cache'
import { redirect } from 'next/navigation'
export async function createPost(formData) {
const session = await auth()
if (!session?.user) {
throw new Error('Unauthorized')
}
// 修改数据
// ...
revalidatePath('/posts')
redirect('/posts')
}调用 redirect 会抛出一个由框架处理的控制流异常。其后的任何代码都不会执行。如果你需要最新数据,请提前调用 revalidatePath 或 revalidateTag。
Cookies#
你可以使用 cookies API 在 Server Action 中 get、set 和 delete cookie。
当你在 Server Action 中设置或删除 cookie 时,Next.js 会在服务器上重新渲染当前页面及其布局,以便 UI 反映新的 cookie 值。
小知识:服务器端更新会应用于当前 React 树,根据需要重新渲染、挂载或卸载组件。重新渲染的组件会保留客户端状态,并且如果依赖项发生变化,effect 会重新运行。
'use server'
import { cookies } from 'next/headers'
export async function exampleAction() {
const cookieStore = await cookies()
// 获取 cookie
cookieStore.get('name')?.value
// 设置 cookie
cookieStore.set('name', 'Delba')
// 删除 cookie
cookieStore.delete('name')
}'use server'
import { cookies } from 'next/headers'
export async function exampleAction() {
// 获取 cookie
const cookieStore = await cookies()
// 获取 cookie
cookieStore.get('name')?.value
// 设置 cookie
cookieStore.set('name', 'Delba')
// 删除 cookie
cookieStore.delete('name')
}useEffect#
你可以使用 React 的 useEffect hook 在组件挂载或依赖项变化时调用 Server Action。这适用于依赖全局事件或需要自动触发的数据修改。例如,用于应用快捷方式的 onKeyDown、用于无限滚动的 intersection observer hook,或在组件挂载时更新浏览量:
'use client'
import { incrementViews } from './actions'
import { useState, useEffect, useTransition } from 'react'
export default function ViewCount({ initialViews }: { initialViews: number }) {
const [views, setViews] = useState(initialViews)
const [isPending, startTransition] = useTransition()
useEffect(() => {
startTransition(async () => {
const updatedViews = await incrementViews()
setViews(updatedViews)
})
}, [])
// 你可以使用 `isPending` 为用户提供反馈
return <p>Total Views: {views}</p>
}'use client'
import { incrementViews } from './actions'
import { useState, useEffect, useTransition } from 'react'
export default function ViewCount({ initialViews }) {
const [views, setViews] = useState(initialViews)
const [isPending, startTransition] = useTransition()
useEffect(() => {
startTransition(async () => {
const updatedViews = await incrementViews()
setViews(updatedViews)
})
}, [])
// 你可以使用 `isPending` 为用户提供反馈
return <p>Total Views: {views}</p>
}