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

React中点击重置按钮时如何重置useFormState返回的状态?

解决React Server Action中重置useFormState状态的问题

要同时完成表单重置和useFormState返回的结果重置,你可以通过以下步骤实现:

步骤1:修改重置按钮的点击事件

给现有的type="reset"按钮添加onClick回调,调用useFormState返回的submitAction并传递重置标识:

<button type="reset" onClick={() => submitAction({ reset: true })}>
  Reset
</button>

步骤2:更新Server Action逻辑

在action.ts的submitAction中,判断是否收到重置请求,若是则返回初始状态(null):

// action.ts
export async function submitAction(formData: FormData | { reset: boolean }) {
  // 识别重置请求
  if ('reset' in formData && formData.reset) {
    return null; // 返回初始状态,触发useFormState重置
  }

  // 原有表单计算逻辑
  const data = Object.fromEntries(formData as FormData);
  // ... 你的计算处理代码
  return calculationResult;
}

步骤3:修正组件笔误(可选)

你的代码里存在一处笔误:useFormState(submitForm, null)应该改为useFormState(submitAction, null),匹配你导入的Server Action名称。

方案原理

  • type="reset"会自动清空表单输入框的状态;
  • 调用submitAction({ reset: true })会触发useFormState更新,将result重置为初始的null,表格随之显示"No data available"。

备选方案(无需修改Server Action)

如果不想改动Server Action,也可以用本地状态覆盖的方式:

import { useState } from 'react';
import { useFormState, useFormStatus } from 'react-dom'
import { submitAction } from './action.ts'

export default function Calculator() {
  const [localResetFlag, setLocalResetFlag] = useState(null);
  const [serverResult, submitAction] = useFormState(submitAction, null);
  
  // 优先使用本地重置状态,实现UI层面的结果清空
  const result = localResetFlag ?? serverResult;

  return (
   <>
    <form action={submitAction}>
      [input fields]

      <button 
        type="reset"
        onClick={() => setLocalResetFlag(null)}
      >
        Reset
      </button>
      <CalculateButton />
    </form>

    {/* 表格部分保持不变,使用合并后的result */}
    <Table headers={inputsCols}>
        {result ? (
          Object.entries(result).map(([rowKey, rowData], rowIndex) => (
            <TableRow key={rowIndex}>
              <TableCell key={rowKey} className="font-bold">
                {rowKey}
              </TableCell>

              {Object.entries(rowData).map(([dataKey, dataValue]) => (
                <TableCell key={`${rowKey}-${dataKey}`}>{dataValue}</TableCell>
              ))}
            </TableRow>
          ))
        ) : (
          <TableRow>
            <TableCell colSpan={inputsCols.length}>No data available</TableCell>
          </TableRow>
        )}
      </Table>
    </>
  )
}

// CalculateButton组件保持不变
function CalculateButton() {
  const { pending } = useFormStatus()

  return (
    <Button
      type="submit"
      color="orange"
      disabled={pending}
      icon={pending ? LoadingIcon : undefined}
    >
      Calculate
    </Button>
  )
}

推荐第一种方案,它更贴合React Server Components的设计模式,保证状态更新的一致性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 00:40:11