</> watch:
some overloads
此方法将监视指定的输入并返回它们的值。它对于渲染输入值和确定按条件渲染什么很有用。
¥This method will watch specified inputs and return their values. It is useful to render input value and for determining what to render by condition.
重载
¥Overloads
此功能主要有两个用途:
¥This function mainly serves two purposes:
-
返回并与字段值 a 保持同步。
watch(name: string, defaultValue?): unknown
b.watch(names: string[], defaultValue?): {[key:string]: unknown}
c.watch(): {[key:string]: unknown}
¥Returns and keep sync with fields' values a.
watch(name: string, defaultValue?): unknown
b.watch(names: string[], defaultValue?): {[key:string]: unknown}
c.watch(): {[key:string]: unknown}
-
使用给定的回调函数开始订阅(可以通过调用
unsubscribe
函数停止)a。watch(callback: (data, { name, type }) => void, defaultValues?): { unsubscribe: () => void }
¥Start subscribing with given callback function (can be stopped by calling
unsubscribe
function) a.watch(callback: (data, { name, type }) => void, defaultValues?): { unsubscribe: () => void }
下面是这四个重载中的每一个的解释。
¥The explanation of each of these four overloads follows below.
1-a.监视单个字段 watch(name: string, defaultValue?: unknown): unknown
¥1-a. Watching single field watch(name: string, defaultValue?: unknown): unknown
监视并订阅渲染之外使用的单个字段。
¥Watch and subscribe to a single field used outside of render.
参数
¥Params
名称 | 类型 | 描述 |
---|---|---|
name | string | 字段名称 |
defaultValue | unknown | 可选。字段的默认值 |
返回单个字段值。
¥Returns the single field value.
const name = watch("name")
1-b.监视某些字段 watch(names: string[], defaultValue?: {[key:string]: unknown}): unknown[]
¥1-b. Watching some fields watch(names: string[], defaultValue?: {[key:string]: unknown}): unknown[]
监视并订阅渲染之外使用的字段数组。
¥Watch and subscribe to an array of fields used outside of render.
参数
¥Params
名称 | 类型 | 描述 |
---|---|---|
names | string[] | 字段名称 |
defaultValue | {[key:string]: unknown} | 可选。字段的默认值 |
返回字段值数组。
¥Returns an array of field values.
const [name, name1] = watch(["name", "name1"])
1-c.监视整个表单 watch(): {[key:string]: unknown}
¥1-c. Watching the entire form watch(): {[key:string]: unknown}
根据 onChange 监视并订阅整个表单的更新/更改,并在 useForm 上重新渲染。
¥Watch and subscribe to the entire form update/change based on onChange and re-render at the useForm.
参数无
¥Params None
返回整个表单值。
¥Returns the entire form values.
const formValues = watch()
2. 使用回调 fn watch(callback: (data, { name, type }) => void, defaultValues?: {[key:string]: unknown}): { unsubscribe: () => void }
开始监视
¥ Start watching with callback fn watch(callback: (data, { name, type }) => void, defaultValues?: {[key:string]: unknown}): { unsubscribe: () => void }
订阅字段更新/更改而不触发重新渲染。
¥Subscribe to field update/change without trigger re-render.
参数
¥Params
名称 | 类型 | 描述 |
---|---|---|
callback | (data, { name, type }) => void | 回调函数以订阅所有字段更改 |
defaultValues | {[key:string]: unknown} | 可选。整个表单的默认值 |
返回具有 unsubscribe
函数的对象。
¥Returns object with unsubscribe
function.
useEffect(() => {const { unsubscribe } = watch((value) => {console.log(value)})return () => unsubscribe()}, [watch])
规则
¥Rules
-
当
defaultValue
未定义时,watch
的第一次渲染将返回undefined
,因为它在register
之前被调用。建议在useForm
处提供defaultValues
以避免这种行为,但你可以将内联defaultValue
设置为第二个参数。¥When
defaultValue
is not defined, the first render ofwatch
will returnundefined
because it is called beforeregister
. It's recommended to providedefaultValues
atuseForm
to avoid this behaviour, but you can set the inlinedefaultValue
as the second argument. -
当
defaultValue
和defaultValues
都提供时,将返回defaultValue
。¥When both
defaultValue
anddefaultValues
are supplied,defaultValue
will be returned. -
此 API 将在应用或表单的根部触发重新渲染,如果你遇到性能问题,请考虑使用回调或 useWatch api。
¥This API will trigger re-render at the root of your app or form, consider using a callback or the useWatch api if you are experiencing performance issues.
-
watch
结果针对渲染阶段而不是useEffect
的 deps 进行了优化,为了检测值更新,你可能需要使用外部自定义钩子进行值比较。¥
watch
result is optimised for render phase instead ofuseEffect
's deps, to detect value update you may want to use an external custom hook for value comparison.
示例:
¥Examples:
在表单中监视
¥Watch in a Form
import React from "react"import { useForm } from "react-hook-form"interface IFormInputs {name: stringshowAge: booleanage: number}function App() {const {register,watch,formState: { errors },handleSubmit,} = useForm<IFormInputs>()const watchShowAge = watch("showAge", false) // you can supply default value as second argumentconst watchAllFields = watch() // when pass nothing as argument, you are watching everythingconst watchFields = watch(["showAge", "age"]) // you can also target specific fields by their names// Callback version of watch. It's your responsibility to unsubscribe when done.React.useEffect(() => {const subscription = watch((value, { name, type }) =>console.log(value, name, type))return () => subscription.unsubscribe()}, [watch])const onSubmit = (data: IFormInputs) => console.log(data)return (<><form onSubmit={handleSubmit(onSubmit)}><input {...register("name", { required: true, maxLength: 50 })} /><input type="checkbox" {...register("showAge")} />{/* based on yes selection to display Age Input*/}{watchShowAge && (<input type="number" {...register("age", { min: 50 })} />)}<input type="submit" /></form></>)}
在字段数组中监视
¥Watch in Field Array
import * as React from "react"import { useForm, useFieldArray } from "react-hook-form"type FormValues = {test: {firstName: stringlastName: string}[]}function App() {const { register, control, handleSubmit, watch } = useForm<FormValues>()const { fields, remove, append } = useFieldArray({name: "test",control,})const onSubmit = (data: FormValues) => console.log(data)console.log(watch("test"))return (<form onSubmit={handleSubmit(onSubmit)}>{fields.map((field, index) => {return (<div key={field.id}><inputdefaultValue={field.firstName}{...register(`test.${index}.firstName`)}/><inputdefaultValue={field.lastName}{...register(`test.${index}.lastName`)}/><button type="button" onClick={() => remove(index)}>Remove</button></div>)})}<buttontype="button"onClick={() =>append({firstName: "bill" + renderCount,lastName: "luo" + renderCount,})}>Append</button></form>)}
视频
¥Video