我在使用 react-hook-form
时遇到了一些问题,并且 defaultValues 消失了
所以我使用默认值启动 useForm,然后从我们的 API 获取异步用户位置。我想根据我们的用户数据预先填写国家/地区。
不幸的是,在我这样做之后,payment
属性中的所有默认值都丢失了。
为什么会发生这种情况,我该如何解决?
我试图找到一些解决方案,但似乎都没有帮助我(setTimeout
、useMemo
on defaultValues 等)
const form = useForm<CheckoutFormSteps>({
defaultValues: {
team: {
id: null,
icon: 'url',
name: 'someName',
},
payment: {
address1: '',
address2: '',
city: '',
companyName: '',
paymentMethod: PaymentMethod.CreditCard,
country: '',
firstName: '',
lastName: '',
phone: '',
postalCode: '',
state: '',
vat_number: '',
},
},
});
useEffect(() => {
// some async logic to get user's country
form.setValue('payment.country', 'US');
// also tried setTimeout(() => form.setValue('payment.country', 'AU'));
}, []);
然后 getValues 看起来像
{
team: {
id: null,
icon: 'url',
name: 'someName',
},
payment: {
country: 'US',
} // all other payment props are gone
}
答案 0 :(得分:0)
给你一个解决方案
const form = useForm<CheckoutFormSteps>({
defaultValues: {
team: {
id: null,
icon: 'url',
name: 'someName',
},
payment: {
address1: '',
address2: '',
city: '',
companyName: '',
paymentMethod: PaymentMethod.CreditCard,
country: '',
firstName: '',
lastName: '',
phone: '',
postalCode: '',
state: '',
vat_number: '',
},
},
});
useEffect(() => {
// some async logic to get user's country
form.setValue({
...form,
payment: {
...form.payment,
country: "US"
}
});
// also tried setTimeout(() => form.setValue('payment.country', 'AU'));
}, []);
无论何时设置值,都需要保留旧值作为值。出于同样的原因,请使用扩展运算符。