React Hook表单不更新值如果默认值是数组



我正在创建一个从模板读取文件的动态生成的表单。我有一组"问题"它们被映射到一个反应钩子形式。我使用的defaultValues是一个对象数组。我遇到的问题是在react-hook-form控制器中使用react-select,因为它不设置表单状态,如果它是一个数组。在我的测试中,如果默认值不是数组,它可以正常工作。请参阅我的MRE代码示例

const questions = [
{
value: '',
}];
const options = [
{ value: 'chocolate', label: 'Chocolate' },
{ value: 'strawberry', label: 'Strawberry' },
{ value: 'vanilla', label: 'Vanilla' },
];
export default function Form()
{
const methods = useForm({
defaultValues: questions,
});
const onSubmit = (data: any) => console.log(data);
return (
<form onSubmit={methods.handleSubmit(onSubmit)}>
<Controller
name="0.value"
control={methods.control}
render={({ field }) => (
<Select
{...field}
value={options.find((c) => c.value === field.value)}
options={options}
onChange={(e) => field.onChange(e?.value)}
/>
)}
/>
<button type="submit">Submit</button>
</form>
);
}

让react-hook形式的控制器组件(如react-select)与defaultValues数组一起工作的最佳方法是什么

您遇到的问题是由于您的默认值是数组而不是对象。你应该把你的问题包装在一个对象中,并选择一个键。

const questions = [
{
value: '',
}];
const options = [
{ value: 'chocolate', label: 'Chocolate' },
{ value: 'strawberry', label: 'Strawberry' },
{ value: 'vanilla', label: 'Vanilla' },
];
export default function Form()
{
const methods = useForm({
defaultValues: {questions},
});
const onSubmit = (data: any) => console.log(data);
return (
<form onSubmit={methods.handleSubmit(onSubmit)}>
<Controller
name="questions.0.value"
control={methods.control}
render={({ field }) => (
<Select
{...field}
value={options.find((c) => c.value === field.value)}
options={options}
onChange={(e) => field.onChange(e?.value)}
/>
)}
/>
<button type="submit">Submit</button>
</form>
);