ค้นหาเว็บไซต์

javascript - การอัปเดตค่าภายใน useFieldArray/react-hook-form


ฉันกำลังหาความช่วยเหลือเกี่ยวกับปัญหาในการใช้ react-hook-form/useFieldArray

ฉันมีอาเรย์แบบนี้:

[ 
  {name: "one", data: "long string"},
  {name: "two", data: "another long string"},
]

อาร์เรย์นี้อยู่ภายในฟอร์มและถูกแสดงผลด้วยความช่วยเหลือของ useFieldArray

ตอนนี้ฉันต้องการตั้งค่า data ใหม่บนองค์ประกอบตัวแรก เอกสารของ react-hook-form ให้ฟังก์ชัน "update" ดังนี้:

เนื่องจากฉันไม่ต้องการทำให้เกิดการติดตั้งใหม่ ฉันจึงใช้ API setValue แบบนี้:

form.setValue("array.0.data", newValue);

เมื่อฉันทำเช่นนั้น ฉันจะได้ค่าใหม่โดยใช้ฟังก์ชัน form.watch และ form.getValues แต่เมื่อฉันสอบถามค่าของฟิลด์โดยใช้ array.fields[0].data ฉันยังคงได้รับค่าเดิมอยู่

ฉันจะขอบคุณมากสำหรับความช่วยเหลือเกี่ยวกับวิธีการอัปเดตค่าหนึ่งค่าในอาร์เรย์และรับค่าที่อัปเดตใหม่ทั้งในฟิลด์และในฟอร์มโดยไม่ต้องทำให้เกิดการรีเมานท์

ด้วยความนับถือ, โทบิอัส

คำตอบ #1

แรกจะเป็นตัวอย่างและจากนั้นก็จะเป็นคำอธิบาย

วิธีการในการทำการเปลี่ยนแปลง:

const setSkuDescription = (
    value: string,
    index: number,
    field: FieldArrayWithId<Fields, 'product', 'id'>
): void => {
    update(index, {
        ...field, // all the info in the current object field this is required and not partial (they say is in the doc)
        productID: value, // one of the fields i want to update
        skuDescriptions: rawProducts // another field i want to update
            .map((p) => {
                if (p.ta_name === value) return p;
            })
            .filter((p) => p !== undefined) as Product[]
    });
};

ที่ที่ฉันกำลังใช้วิธีนี้:

<CFormSelect
// this is for reference to you to see where to use the method
  onChange={(d) => setSkuDescription(d.currentTarget.value, index, field)
}>
    <option hidden>---</option>
    {products.map((product, key) => (
        <option value={product.value as string} key={key}>
           {product.label}
        </option>
     ))}
</CFormSelect>

ที่ซึ่งมีการสะท้อนการเปลี่ยนแปลง

<CFormSelect
{...register("product.${index}.description", { // this is for reference to you to see where the method will render in the HTML if you need it
     required: "The field SKU Description is required"
 })}>
     <option hidden>---</option>
     {field.skuDescriptions.map((p, key) => (
         <option value={p.ta_productid as string} key={key}>
            {p.ta_size}
         </option>
      ))}
</CFormSelect>

คำอธิบาย: ขั้นแรกคือวิธีการที่รับพารามิเตอร์ 3 ตัว คือ "value" ที่คุณต้องการแก้ไข ตัวที่สองคือดัชนีของอาร์เรย์ที่อาร์เรย์ให้คุณเมื่อทำการแมป และสุดท้ายคือวัตถุฟิลด์ทั้งหมดที่ส่งกลับการแมปของอาร์เรย์ เนื่องจากสิ่งนี้จำเป็นต้องใช้ในการอัปเดตข้อมูลทั้งหมดของอ็อบเจ็กต์ (ส่วนนี้อ้างอิงจากเอกสารอย่างเป็นทางการ)

ข้อมูลที่จำเป็นในเอกสาร

บทความที่เกี่ยวข้อง