</> formState:
Object
此对象包含有关整个表单状态的信息。它可以帮助你跟踪用户与表单应用的交互。
¥This object contains information about the entire form state. It helps you to keep on track with the user's interaction with your form application.
返回
¥Return
名称 | 类型 | 描述 |
---|---|---|
isDirty | boolean | 在用户修改任何输入后设置为 true 。
|
dirtyFields | object | 具有用户修改字段的对象。确保通过 useForm 提供所有输入的 defaultValues ,以便库可以与 defaultValues.
|
touchedFields | object | 包含用户交互过的所有输入的对象。 |
defaultValues | object | 已在 useForm 的 defaultValues 或通过 reset API 更新的 defaultValues 中设置的值。 |
isSubmitted | boolean | 提交表单后设置为 true 。将保持 true ,直到调用 reset 方法。 |
isSubmitSuccessful | boolean | 表明表单已成功提交,没有任何运行时错误。 |
isSubmitting | boolean | true (如果当前正在提交表单)。否则为 false 。 |
isLoading | boolean | 如果表单当前正在加载异步默认值,则为 true 。
|
submitCount | number | 表单提交的次数。 |
isValid | boolean | 如果表单没有任何错误,则设置为 true 。
|
isValidating | boolean | 验证期间设置为 true 。 |
validatingFields | boolean | 捕获正在进行异步验证的字段。 |
errors | object | 存在字段错误的对象。还有一个 ErrorMessage 组件可以轻松检索错误消息。 |
disabled | boolean | 如果通过 useForm 中的 disabled 属性禁用表单,则设置为 true。 |
返回的
formState
用 代理 封装,以提高渲染性能,如果未订阅特定状态,则跳过额外逻辑。因此,请确保在渲染之前调用或读取它以启用状态更新。¥Returned
formState
is wrapped with a Proxy to improve render performance and skip extra logic if specific state is not subscribed to. Therefore make sure you invoke or read it before a render in order to enable the state update.formState
批量更新。如果你想通过useEffect
订阅formState
,请确保将整个formState
放在可选数组中。¥
formState
is updated in batch. If you want to subscribe toformState
viauseEffect
, make sure that you place the entireformState
in the optional array.useEffect(() => {if (formState.errors.firstName) {// do the your logic here}}, [formState]) // ✅// ❌ [formState.errors] will not trigger the useEffect订阅
formState
时请注意逻辑运算符。¥Pay attention to the logical operator when subscription to
formState
.// ❌ formState.isValid is accessed conditionally,// so the Proxy does not subscribe to changes of that statereturn <button disabled={!formState.isDirty || !formState.isValid} />;// ✅ read all formState values to subscribe to changesconst { isDirty, isValid } = formState;return <button disabled={!isDirty || !isValid} />;
示例
¥Examples
import React from "react";import { useForm } from "react-hook-form";export default function App() {const {register,handleSubmit,// Read the formState before render to subscribe the form state through the ProxyformState: { errors, isDirty, isSubmitting, touchedFields, submitCount },} = useForm();const onSubmit = (data) => console.log(data);return (<form onSubmit={handleSubmit(onSubmit)}><input {...register("test")} /><input type="submit" /></form>);}
视频
¥Video