服务器操作允许客户端组件调用在服务器上执行的异步函数。
¥Server Actions allow Client Components to call async functions executed on the server.
- 从服务器组件创建服务器操作
- 从客户端组件导入服务器操作
- 使用操作编写服务器操作
- 使用服务器操作的表单操作
- 使用
useActionState
的服务器操作 - 使用
useActionState
进行渐进式增强
当使用 "use server"
指令定义服务器操作时,你的框架将自动创建对服务器函数的引用,并将该引用传递给客户端组件。当在客户端调用该函数时,React 将向服务器发送请求以执行该函数并返回结果。
¥When a Server Action is defined with the "use server"
directive, your framework will automatically create a reference to the server function, and pass that reference to the Client Component. When that function is called on the client, React will send a request to the server to execute the function, and return the result.
服务器操作可以在服务器组件中创建并作为属性传递给客户端组件,也可以在客户端组件中导入和使用。
¥Server Actions can be created in Server Components and passed as props to Client Components, or they can be imported and used in Client Components.
从服务器组件创建服务器操作
¥Creating a Server Action from a Server Component
服务器组件可以使用 "use server"
指令定义服务器操作:
¥Server Components can define Server Actions with the "use server"
directive:
// Server Component
import Button from './Button';
function EmptyNote () {
async function createNoteAction() {
// Server Action
'use server';
await db.notes.create();
}
return <Button onClick={createNoteAction}/>;
}
当 React 渲染 EmptyNote
服务器组件时,它将创建对 createNoteAction
函数的引用,并将该引用传递给 Button
客户端组件。当单击按钮时,React 将使用提供的引用向服务器发送请求以执行 createNoteAction
函数:
¥When React renders the EmptyNote
Server Component, it will create a reference to the createNoteAction
function, and pass that reference to the Button
Client Component. When the button is clicked, React will send a request to the server to execute the createNoteAction
function with the reference provided:
"use client";
export default function Button({onClick}) {
console.log(onClick);
// {$$typeof: Symbol.for("react.server.reference"), $$id: 'createNoteAction'}
return <button onClick={() => onClick()}>Create Empty Note</button>
}
有关更多信息,请参阅 "use server"
的文档。
¥For more, see the docs for "use server"
.
从客户端组件导入服务器操作
¥Importing Server Actions from Client Components
客户端组件可以从使用 "use server"
指令的文件中导入服务器操作:
¥Client Components can import Server Actions from files that use the "use server"
directive:
"use server";
export async function createNoteAction() {
await db.notes.create();
}
当打包器构建 EmptyNote
客户端组件时,它将在打包包中创建对 createNoteAction
函数的引用。当单击 button
时,React 将使用提供的引用向服务器发送请求以执行 createNoteAction
函数:
¥When the bundler builds the EmptyNote
Client Component, it will create a reference to the createNoteAction
function in the bundle. When the button
is clicked, React will send a request to the server to execute the createNoteAction
function using the reference provided:
"use client";
import {createNoteAction} from './actions';
function EmptyNote() {
console.log(createNoteAction);
// {$$typeof: Symbol.for("react.server.reference"), $$id: 'createNoteAction'}
<button onClick={createNoteAction} />
}
有关更多信息,请参阅 "use server"
的文档。
¥For more, see the docs for "use server"
.
使用操作编写服务器操作
¥Composing Server Actions with Actions
服务器操作可以与客户端上的操作组合:
¥Server Actions can be composed with Actions on the client:
"use server";
export async function updateName(name) {
if (!name) {
return {error: 'Name is required'};
}
await db.users.updateName(name);
}
"use client";
import {updateName} from './actions';
function UpdateName() {
const [name, setName] = useState('');
const [error, setError] = useState(null);
const [isPending, startTransition] = useTransition();
const submitAction = async () => {
startTransition(async () => {
const {error} = await updateName(name);
if (!error) {
setError(error);
} else {
setName('');
}
})
}
return (
<form action={submitAction}>
<input type="text" name="name" disabled={isPending}/>
{state.error && <span>Failed: {state.error}</span>}
</form>
)
}
这允许你通过将服务器操作封装在客户端上的操作中来访问服务器操作的 isPending
状态。
¥This allows you to access the isPending
state of the Server Action by wrapping it in an Action on the client.
有关更多信息,请参阅 调用 <form>
外部的服务器操作 的文档
¥For more, see the docs for Calling a Server Action outside of <form>
使用服务器操作的表单操作
¥Form Actions with Server Actions
服务器操作可与 React 19 中的新表单功能配合使用。
¥Server Actions work with the new Form features in React 19.
你可以将服务器操作传递给表单以自动将表单提交到服务器:
¥You can pass a Server Action to a Form to automatically submit the form to the server:
"use client";
import {updateName} from './actions';
function UpdateName() {
return (
<form action={updateName}>
<input type="text" name="name" />
</form>
)
}
当表单提交成功时,React 将自动重置表单。你可以添加 useActionState
来访问待处理状态、最后响应或支持渐进增强。
¥When the Form submission succeeds, React will automatically reset the form. You can add useActionState
to access the pending state, last response, or to support progressive enhancement.
有关更多信息,请参阅 表单中的服务器操作 的文档。
¥For more, see the docs for Server Actions in Forms.
使用 useActionState
的服务器操作
¥Server Actions with useActionState
对于只需要访问操作待处理状态和最后返回响应的常见情况,你可以使用 useActionState
编写服务器操作:
¥You can compose Server Actions with useActionState
for the common case where you just need access to the action pending state and last returned response:
"use client";
import {updateName} from './actions';
function UpdateName() {
const [state, submitAction, isPending] = useActionState(updateName, {error: null});
return (
<form action={submitAction}>
<input type="text" name="name" disabled={isPending}/>
{state.error && <span>Failed: {state.error}</span>}
</form>
);
}
当将 useActionState
与服务器操作一起使用时,React 还将自动重放在水化完成之前输入的表单提交。这意味着用户甚至可以在应用完成水合之前与你的应用进行交互。
¥When using useActionState
with Server Actions, React will also automatically replay form submissions entered before hydration finishes. This means users can interact with your app even before the app has hydrated.
有关更多信息,请参阅 useActionState
的文档。
¥For more, see the docs for useActionState
.
使用 useActionState
进行渐进式增强
¥Progressive enhancement with useActionState
服务器操作还支持使用 useActionState
的第三个参数进行渐进增强。
¥Server Actions also support progressive enhancement with the third argument of useActionState
.
"use client";
import {updateName} from './actions';
function UpdateName() {
const [, submitAction] = useActionState(updateName, null, `/name/update`);
return (
<form action={submitAction}>
...
</form>
);
}
当将 permalink 提供给 useActionState
时,如果在 JavaScript 包加载之前提交了表单,React 将重定向到提供的 URL。
¥When the permalink is provided to useActionState
, React will redirect to the provided URL if the form is submitted before the JavaScript bundle loads.
有关更多信息,请参阅 useActionState
的文档。
¥For more, see the docs for useActionState
.