reactjs 如何更新react-form-hook中数组的表单数据数组?

fcwjkofz  于 2023-02-22  发布在  React
关注(0)|答案(1)|浏览(225)

最近几天,我在react-form-hook中更新数组中的表单数据时遇到了麻烦。我附上了字段结构、类型等的截图。我想在保存数据时更新字段数据的字段。
我想用 nested arrayuseFieldArray钩子执行它,钩子来自react-hook-form库。
我没有得到任何错误,但数据没有在数据库中正确传递。我该如何修复它?

export const defects = {
  title: 'Defects',
  fields: [
    {
      title: 'Defect Location:',
      name: 'defects.location',
      type: 'checkbox',
      fields: [
        {
          title: 'Interior',
          type: 'checkbox',
          name: 'defects.location.interior',
        },
        {
          title: 'Roof space',
          type: 'checkbox',
          name: 'defects.location.roofSpace',
        },
        {
          title: 'Other',
          type: 'textarea',
          name: 'defects.location.other',
        },
      ],
    },
    {
      title: 'Defect Summary:',
      name: 'defects.summary',
      type: 'checkbox',
      fields: [
        {
          title: 'Roof Framing',
          type: 'checkbox',
          name: 'defects.summary.roofFraming',
        },
        {
          title: 'Porch Support',
          type: 'checkbox',
          name: 'defects.summary.porchSupport',
        },
        {
          title: 'Alfresco Support',
          type: 'checkbox',
          name: 'defects.summary.alfrescoSupport',
        },
        {
          title: 'Gate Feature',
          type: 'checkbox',
          name: 'defects.summary.gateFeature',
        },
        {
          title: 'Subfloor Structure',
          type: 'checkbox',
          name: 'defects.summary.subfloorStructure',
        },
        {
          title: 'Brick',
          type: 'checkbox',
          name: 'defects.summary.brick',
        },
        {
          title: 'Other',
          type: 'textarea',
        },
      ],
    },
  ],
}

父组件

const { register, handleSubmit, errors, setValue, getValues, control, watch, reset } =
    useForm({ shouldUnregister: false })

  const { fields, append, remove, update } = useFieldArray({
    control: control,
    name: defects.title,
  })

  const onSubmit = async (data) => {
    const values = getValues()
    console.log('data is here', data, values)
    const response = await fetch('/api/db/handler', {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(data),
    })
    if (response.ok) {
      setSaved(true)
      setTimeout(() => {
        setSaved(false)
      }, 2000)
    }
    return response
  }

return(
         <Defects
                data={defects}
                register={register}
                setValue={setValue}
                control={control}
                watch={watch}
                fields={fields}
                append={append}
                remove={remove}
                update={update}
              />
    )

JS缺陷

const Defects = ({
  register,
  setValue,
  control,
  watch,
  data,
  fields,
  append,
  remove,
  update,
}) => {
  useEffect(() => {
    update();
  }, [register]);

  return (
    <div>
     
      {fields.map((props, index) => {
        return (
          <Disclosure
            defaultOpen
            open={true}
            as='div'
            key={props.id}
            className='border-b-4 p-4 border-gray-100'
          >
            {index > 0 ? (
              <div className='flex items-center'>
                <Disclosure.Button className='text-xl uppercase underline flex items-center'>
                  {`DEFEECT ${index}`}
                  <FaChevronDown className='ml-4 ui-open:rotate-180 ui-open:transform' />
                </Disclosure.Button>
                <button
                  className='bg-sky-400 text-white px-4 py-2 rounded mt-4 ml-12'
                  onClick={() => remove(index)}
                >
                  Delete
                </button>
              </div>
            ) : (
              <div className='flex items-center'>
                <Disclosure.Button className='text-xl uppercase underline flex items-center'>
                  DEFEECTS
                  <FaChevronDown className='ml-4 ui-open:rotate-180 ui-open:transform' />
                </Disclosure.Button>
              </div>
            )}
            {props.fields.map((field, i) => {
              return (
                <Disclosure.Panel
                  key={field.title + i}
                  className='grid grid-cols-[minmax(min-content,.5fr)_minmax(300px,1fr)] my-4'
                >
                  {field.sectionTitle && (
                    <h3 className='col-span-2 text-lg border-b-4 mb-2 border-b-gray-100 uppercase'>
                      {field.sectionTitle}
                    </h3>
                  )}
                  <h3>{field.title}</h3>
                 
                  {field.type == 'checkbox' && (
                    <Checkbox
                      data={field}
                      register={register}
                      setValue={setValue}
                      nestedIndex={index}
                      fieldName={field.name}
                      fieldIndex={i}
                    />
                  )}
                
                </Disclosure.Panel>
              );
            })}
          </Disclosure>
        );
      })}
    </div>
  );
};

复选框JS

import React from 'react';

const Checkbox = ({  data,
  register,
  setValue,
  nestedIndex = null,
  fieldName = '',
  fieldIndex = null,}) => {
  return (
    <div className='flex flex-col justify-start items-start'>
      {data.fields.map((item, index) => {
            return (
              // eslint-disable-next-line react/jsx-key

              <div
                key={`${item.title}${index}`}
                className='flex flex-row items-center'
              >
                <label className='mr-2' htmlFor={item.name}>
                  {item.title}
                </label>
                <input
                  type={item.type}
                  name={`Defects[${nestedIndex}].fields[${fieldIndex}].fields[${index}].${item.name}`}
                  className={`${
                    item.type == 'textarea' && 'w-full'
                  } border border-gray-100 p-2`}
                  {...register(
                    `Defects[${nestedIndex}].fields[${fieldIndex}].fields[${index}].${item.name}`
                  )}
                />
              </div>
            );
          })}
sr4lhrrt

sr4lhrrt1#

我已经将useForm的钩子的示例传递给子组件,然后在子组件中使用它,正如您在复选框文件中看到的那样,现在它工作正常。

相关问题