You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Next.js服务器组件中获取Server Action的响应信息?

不需要把Action和组件转成客户端实现,Next.js支持在客户端组件中调用Server Action并获取它返回的错误信息,有两种常用方式:

1. 使用useFormState(表单场景推荐)

这是React官方提供的专门处理表单状态的Hook,能直接关联Server Action的返回值,自动处理表单提交后的状态更新。

比如你的登录表单可以这么写:

'use client';

import { useFormState } from 'react-dom';
import { login } from '@/src/actions/auth';

export default function LoginForm() {
  // 初始化状态为空的错误信息
  const [actionState, formAction] = useFormState(login, { message: '' });

  return (
    <form action={formAction}>
      <div>
        <label>邮箱</label>
        <input type="email" name="email" required />
      </div>
      <div>
        <label>密码</label>
        <input type="password" name="password" required />
      </div>
      <button type="submit">登录</button>
      {/* 展示错误信息 */}
      {actionState.message && <p style={{ color: 'red' }}>{actionState.message}</p>}
    </form>
  );
}

2. 在客户端组件中直接异步调用Server Action

如果需要更灵活的控制(比如自定义提交逻辑),可以在客户端组件的事件处理函数里直接await调用Server Action,然后捕获返回的错误信息:

'use client';

import { useState } from 'react';
import { login } from '@/src/actions/auth';

export default function LoginForm() {
  const [errorMsg, setErrorMsg] = useState('');

  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    setErrorMsg(''); // 清空之前的错误
    const formData = new FormData(e.currentTarget);
    const result = await login(formData);
    // 如果返回了错误信息,更新状态展示
    if (result?.message) {
      setErrorMsg(result.message);
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      <div>
        <label>邮箱</label>
        <input type="email" name="email" required />
      </div>
      <div>
        <label>密码</label>
        <input type="password" name="password" required />
      </div>
      <button type="submit">登录</button>
      {errorMsg && <p style={{ color: 'red' }}>{errorMsg}</p>}
    </form>
  );
}

两种方式都能保留Server Action的服务端逻辑,不需要迁移到客户端,只需要确保使用这些逻辑的组件加上'use client'指令即可。

内容的提问来源于stack exchange,提问作者Hesam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 21:52:24