我有一个带有fieldArray的react-hook-form,当我向服务器发送数据时,我写了
const methods = useForm<UserSubmitFormCreate>({
defaultValues: {
contactsArray: [{ fio: "", phone_num: "", email: "" }],
},
mode: "onChange"
});
但是如果我从服务器获取了数据,并且必须在fieldArray中使用它,我尝试写这个:
const methods = useForm<UserSubmitFormCreate>({
defaultValues: {
contactsArray: [{ fio: "John", phone_num: "123", email: "abc@abc.com" }],
},
mode: "onChange"
});
它没有工作。很奇怪,但在我的组件中,我有变量fields
,这个数据是准确的。但在我的字段中,我什么也看不到。这是我的组件的精简版本:
const FieldsArrayInput = () => {
const { control, register } = useFormContext();
const { fields } = useFieldArray({
control,
name: "contactsArray",
});
console.log(fields); // [{ fio: "John", phone_num: "123", email: "abc@abc.com" }]
return (
{fields.map((field: any, index: number) => {
return (
<div key={field.id}>
<input
placeholder="name"
{...register(`contactsArray.${index}.fio` as const,
{
shouldUnregister: true,
required: { value: someReturnedTrueOaFalse(), message: "someMessage" },
})
} />
<input
placeholder="email"
{...register(`contactsArray.${index}.email` as const,
{
shouldUnregister: true,
required: { value: someReturnedTrueOaFalse(), message: "someMessage" },
})
} />
<input
placeholder="phone"
{...register(`contactsArray.${index}.phone_num` as const,
{
shouldUnregister: true,
required: { value: someReturnedTrueOaFalse(), message: "someMessage" },
})
} />
</div>
);
})}
);
};
UPD:当我从服务器获取数据时(例如,有两个对象:[{ fio: "John", phone_num: "123", email: "abc@abc.com" }, { fio: "Elena", phone_num: "456", email: "def@abc.com" }]
)我看到一对字段,但它是空的
1条答案
按热度按时间bvn4nwqk1#
试着给输入赋予名称和值属性。这可能会起作用。就像这样:
如果它没有显示这样的值,尝试给
value={field.fio}
或value={contactsArray[index].fio}
类似的东西。