简体   繁体   English

如何在反应中更新useState挂钩中嵌套的数组object?

[英]how to update nested object of array in useState hook in react?

I have a component that has nested objects in array:我有一个在数组中有嵌套对象的组件:

  const [documentObj, setDocument] = useState({
    document_name: "",
    form_values: [
      {
        field_seq: null,
        is_mandatory: false,
        field_type: null,
        field_name: "",
        select_values: [
          {
            value: false,
            label: "",
          },
        ],
      },
    ],
  });

I'm trying to update the object properties, but when I try to update the object, it is saying can not reay properties [0]我正在尝试更新 object 属性,但是当我尝试更新 object 时,提示无法重新设置属性 [0]

this is how I'm updating it:这就是我更新它的方式:


<Form.Control
 type="number"
 value={documentObj.form_values[0].field_seq}
 onChange={(event) => {
  setDocument((prevStyle) => ({
  ...prevStyle,
form_values: [
{
...prevStyle.form_values,
field_seq: event.target.value,
},
],
}));
}}
/>
</Form.Group>

Probably i need to write a function to handle all input value and need some help可能我需要写一个 function 来处理所有输入值并需要一些帮助

Update 2更新 2

It seems that documentObj.form_values[0] is unlikely to be undefined in the posted code, but maybe it could be in the actual project.似乎documentObj.form_values[0]不太可能在发布的代码中undefined ,但也许它可能在实际项目中。

As an attempt to address the error perhaps also consider to check for undefined where this is used, such as in value :作为解决该错误的尝试,也许还可以考虑检查使用 this 的地方是否存在undefined ,例如在value中:

value={documentObj.form_values[0]?.field_seq || ""}

Update更新

While not specified in the post, if Form.Control is from react-bootstrap, according to their doc the value property need to be string | arrayOf | number虽然帖子中没有指定,但如果Form.Control来自 react-bootstrap,根据他们的文档value属性需要是string | arrayOf | number string | arrayOf | number string | arrayOf | number . string | arrayOf | number

Perhaps also try set an empty string "" as the initial value of field_seq , so this component is fully controlled:也许也可以尝试设置一个空字符串""作为field_seq的初始值,这样这个组件就可以完全控制了:

const [documentObj, setDocument] = useState({
  document_name: "",
  form_values: [
    {
      // 👇 Initial value as empty string
      field_seq: "",
      is_mandatory: false,
      field_type: null,
      field_name: "",
      select_values: [
        {
          value: false,
          label: "",
        },
      ],
    },
  ],
});

There might be other issues, but hope that this could still help locating some errors.可能还有其他问题,但希望这仍然可以帮助定位一些错误。

Original原来的

Perhaps the intended property to read was ...prevStyle.form_values[0] ?也许要读取的预期属性是...prevStyle.form_values[0]

Not sure if there are other issues without checking the error message, but could probably try the following in setDocument to see if it improves:在不检查错误消息的情况下不确定是否还有其他问题,但可能会在setDocument中尝试以下操作以查看它是否有所改善:

<Form.Control
  type="number"
  value={documentObj.form_values[0].field_seq}
  onChange={(event) => {
    setDocument((prevStyle) => ({
      ...prevStyle,
      form_values: [
        {
          // 👇 Added [0] here
          ...prevStyle.form_values[0],
          field_seq: event.target.value,
        },
      ],
    }));
  }}
/>

const [documentObj, setDocument] = useState({ document_name: "", form_values: [ { field_seq: null, is_mandatory: false, field_type: null, field_name: "", select_values: [ { value: false, label: "", }, ], }, ], }); const [documentObj, setDocument] = useState({ document_name: "", form_values: [ { field_seq: null, is_mandatory: false, field_type: null, field_name: "", select_values: [ { value: false, label: "", } , ], }, ], });

replacing the items in form_values based on index根据索引替换form_values中的项目

<Form.Control
      type="number"
      value={documentObj.form_values[0]?.field_seq ?? ''}
      onChange={(event) => {
        setDocument((prevStyle) => {
   
    
           const newFormValues = [];
    
           if (!!prevStyle.form_values?.length) {
                              // if the form_values was empty 
           const newFormValue = { 
                 // might want to include some default data
                 field_seq: event.target.value 
           }
               newFormValues.push(newFormValue)
           } else {
                //replace first item form_values 
                newFormValues = prevStyle.form_values.map((e, idx) => {
                       if (idx === 0) {
                           return {
                              ...e,
                              field_seq: event.target.value 
                           }
                       } else {
                            return e;
                       }
                })
           }
    
     
           return {
              ...prevStyle,
              form_values: newFormValues
           }
    
    }}
    />
    </Form.Group>

Hope it helps希望能帮助到你

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM