Skip to content

subscribe

订阅表单状态更新(无需渲染)

subscribe: UseFormSubscribe<TFieldValues extends FieldValues>

订阅 formState 的更改和值更新。你可以订阅单个字段或整个表单,同时避免表单更改导致的不必要的重新渲染。

¥Subscribe to formState changes and value updates. You can subscribe to individual fields or the entire form, while avoiding unnecessary re-renders caused by form changes.

属性

¥Props


名称类型描述示例
nameundefined订阅整个表单subscribe()
string[]通过名称订阅多个字段。subscribe({ name: ['firstName', 'lastName'] })
formStatePartial<ReadFormState>选择要订阅的 formState
callbackFunction订阅的回调函数。
exactboolean此属性将为输入名称订阅启用精确匹配。subscribe({ name: 'target', exact: true })
NOTES
  • This function is intended for subscribing to changes only; dispatching state updates or triggering re-renders is not allowed. eg setValue or reset

  • 此函数与 createFormControl.subscribe 功能相同,主要区别在于 createFormControl 可以在 React 组件外部初始化。

    ¥This function shares the same functionality as createFormControl.subscribe, with the key difference being that createFormControl can be initialized outside of a React component.

  • 此函数专用于订阅表单状态(无需渲染),请使用此函数代替 watch 回调函数。

    ¥This function is dedicated for subscribe form state without render, use this function for that instead of watch callback function.

示例:

¥Examples:


import { useForm } from "react-hook-form"
type FormInputs = {
firstName: string
lastName: string
}
export default function App() {
const { register, subscribe } = useForm<FormInputs>()
useEffect(() => {
// make sure to unsubscribe;
const callback = subscribe({
formState: {
values: true
},
callback: ({ values }) => {
console.log(values);
}
})
return () => callback();
// You can also just return the subscribe
// return subscribe();
}, [subscribe])
return (
<form>
<input {...register("firstName", { required: true })} />
<input {...register("lastName", { required: true })} />
</form>
)
}