react-hook-form:未安装时不在提交数据中显示默认值
react-hook-form: Dont show default values in submit data when they are not mounted
我观察到如果我像下面那样提到 defaultValues
const { register, handleSubmit } = useForm({
defaultValues: {
firstName: "test",
lastName: "test2"
}
});
并且不要挂载 lastName
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register("firstName")} />
<input type="submit" />
</form>
我明白了onSubmit
const onSubmit = (data) => {
console.log(JSON.stringify(data, null, 4));
};
我看到以下内容
{
"firstName": "test",
"lastName": "test2"
}
但我希望只看到 firstName
因为我还没有安装 lastName
{
"firstName": "test",
}
您可以为此使用 shouldUnregister
,来自 Docs:
By default, an input value will be retained when input is removed.
However, you can set shouldUnregister
to true to unregister input
during unmount.
const { register, handleSubmit } = useForm({
defaultValues: {
firstName: "test",
lastName: "test2"
},
shouldUnregister: true
});
我观察到如果我像下面那样提到 defaultValues
const { register, handleSubmit } = useForm({
defaultValues: {
firstName: "test",
lastName: "test2"
}
});
并且不要挂载 lastName
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register("firstName")} />
<input type="submit" />
</form>
我明白了onSubmit
const onSubmit = (data) => {
console.log(JSON.stringify(data, null, 4));
};
我看到以下内容
{
"firstName": "test",
"lastName": "test2"
}
但我希望只看到 firstName
因为我还没有安装 lastName
{
"firstName": "test",
}
您可以为此使用 shouldUnregister
,来自 Docs:
By default, an input value will be retained when input is removed. However, you can set
shouldUnregister
to true to unregister input during unmount.
const { register, handleSubmit } = useForm({
defaultValues: {
firstName: "test",
lastName: "test2"
},
shouldUnregister: true
});