Skip to content

formState

表单状态

</> 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


名称类型描述
isDirtyboolean在用户修改任何输入后设置为 true
  • Important: make sure to provide all inputs' defaultValues at the useForm, so hook form can have a single source of truth to compare whether the form is dirty.
    const {
    formState: { isDirty, dirtyFields },
    setValue
    } = useForm({ defaultValues: { test: "" } })
    // isDirty: true ✅
    setValue('test', 'change')
    // isDirty: false because there getValues() === defaultValues ❌
    setValue('test', '')
  • File typed input will need to be managed at the app level due to the ability to cancel file selection and FileList object.
  • Do not support custom object, Class or File object.
dirtyFieldsobject具有用户修改字段的对象。确保通过 useForm 提供所有输入的 defaultValues,以便库可以与 defaultValues.
  • Important: make sure to provide defaultValues at the useForm, so hook form can have a single source of truth to compare each field's dirtiness.
  • Dirty fields will not represent as isDirty formState, because dirty fields are marked field dirty at field level rather the entire form. If you want to determine the entire form state use isDirty instead.
进行比较
touchedFieldsobject包含用户交互过的所有输入的对象。
defaultValuesobject已在 useFormdefaultValues 或通过 reset API 更新的 defaultValues 中设置的值。
isSubmittedboolean提交表单后设置为 true。将保持 true,直到调用 reset 方法。
isSubmitSuccessfulboolean表明表单已成功提交,没有任何运行时错误。
isSubmittingbooleantrue(如果当前正在提交表单)。否则为 false
isLoadingboolean如果表单当前正在加载异步默认值,则为 true
  • Important: this prop is only applicable to async defaultValues
    const {
    formState: { isLoading }
    } = useForm({
    defaultValues: async () => await fetch('/api')
    })
submitCountnumber表单提交的次数。
isValidboolean如果表单没有任何错误,则设置为 true
  • setError has no effect on isValid formState, isValid will always derived via the entire form validation result.
isValidatingboolean验证期间设置为 true
validatingFieldsboolean捕获正在进行异步验证的字段。
errorsobject存在字段错误的对象。还有一个 ErrorMessage 组件可以轻松检索错误消息。
disabledboolean如果通过 useForm 中的 disabled 属性禁用表单,则设置为 true。
RULES
  • 返回的 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 to formState via useEffect, make sure that you place the entire formState in the optional array.

    useEffect(() => {
    if (formState.errors.firstName) {
    // do the your logic here
    }
    }, [formState]) // ✅
    // ❌ [formState.errors] will not trigger the useEffect
    import { useForm } from "react-hook-form";
    export default function App () {
    const {
    register,
    handleSubmit,
    formState
    } = useForm();
    const onSubmit = (data) => console.log(data);
    React.useEffect(() => {
    console.log("touchedFields", formState.touchedFields);
    },[formState]); // use entire formState object as optional array arg in useEffect, not individual properties of it
    return (
    <form onSubmit={handleSubmit(onSubmit)}>
    <input {...register("test")} />
    <input type="submit" />
    </form>
    );
    };
  • 订阅 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 state
    return <button disabled={!formState.isDirty || !formState.isValid} />;
    // ✅ read all formState values to subscribe to changes
    const { 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 Proxy
formState: { 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