【问题标题】:How the update/change the value of object in array in react js?react js中如何更新/更改数组中对象的值?
【发布时间】:2020-09-22 05:34:57
【问题描述】:

我有一个数组。哪个名字是dynamicform,这个数组中的这个有对象

const dynamicform =[ {
      id: Math.round(Math.random() * 36 ** 12).toString(36),
      mainlabel: checklistlabel,
      type: inputtype,
      grid: inputgrid,
      CheckLists: [
        {
          type: 'checkbox',
          label: "Label one",
        },
      ],
    },
{
   id:id: Math.round(Math.random() * 36 ** 12).toString(36),
   name:"john",
   type:"text"
}]

我只想在 CheckLists Array 中推送一个新对象,所以我写了这个

  setDyanmicForm([
        ...dynamicform,
    dynamicform.map((form, idx) =>
      form.CheckLists.push({
        type: 'checkbox',
        label: defualtchecklabel,
      })
    )
     ]);

但显示错误

TypeError: 无法读取未定义的属性“push”

【问题讨论】:

  • 您需要一些唯一标识符来跟踪您需要在哪个对象中更新值。你的 id 不是唯一的,这里面哪个字段是唯一的?

标签: javascript arrays reactjs


【解决方案1】:

出现上述错误是因为 dynamicForm 中存在第二个元素。看,该元素内没有 CheckLists 属性。

您可以添加对 CheckLists 存在的检查,或者如果您必须为每个项目推送该元素,则可以执行以下操作。

form.CheckLists = form.CheckLists || [];

在将元素推入清单之前添加。

注意:您不会从地图中解构您的结果。正确解构它,否则你会得到一个数组作为 setDyanmicForm 中的元素。

【讨论】:

    猜你喜欢
    • 2021-07-07
    • 2021-11-19
    • 2019-08-03
    • 1970-01-01
    • 1970-01-01
    • 2022-11-18
    • 2023-01-19
    • 1970-01-01
    • 2020-07-18
    相关资源
    最近更新 更多