reactjs 无法以React挂钩形式获取字段数组的默认值

fnatzsnv  于 2023-03-12  发布在  React
关注(0)|答案(1)|浏览(92)

我有一个带有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" }])我看到一对字段,但它是空的

bvn4nwqk

bvn4nwqk1#

试着给输入赋予名称和值属性。这可能会起作用。就像这样:

<input
              placeholder="name"
              {...register(`contactsArray.${index}.fio` as const,
                {
                  shouldUnregister: true,
                  required: { value: someReturnedTrueOaFalse(), message: "someMessage" },
                })
              } 
name="fio" value={fio}
     />

如果它没有显示这样的值,尝试给value={field.fio}value={contactsArray[index].fio}类似的东西。

相关问题