使用React Hooks更新嵌套数组的状态

时间:2020-06-25 16:05:24

标签: reactjs

我已经使用React Hooks已有一段时间了,但是对我来说最大的问题是使用数组。

如何更新对象嵌套数组的值?我想更改下拉类型。 我的代码在下面,并直接更改状态。我怎样才能解决这个问题?什么是最正确的代码?

感谢您的帮助。

  const [grups, setGrups] = useState([
    {
      id: 1,
      css: "col",
      components: [
        { id: 1, type: "textbox" },
        { id: 2, type: "integer" },
      ],
    },

    {
      id: 2,
      css: "col",
      components: [
        { id: 1, type: "numerictextbox" },
        **{ id: 2, type: "dropdown" },**
      ],
    },
  ]);


 function handleClick(gindex,cindex) {
    const newgrups = [...grups];
    newgrups[gindex] = {...grups[gindex] ,components: [...grups[gindex].components]};
    newgrups[gindex].components[cindex].tip="datetime";
    setGrups(newgrups);

  }

2 个答案:

答案 0 :(得分:0)

所以你需要类似的东西

function handleClick(gindex, cindex) {
  // use map to create a new array and at the same time
  // modify the contents when required
  const newgrups = grups.map((grup, gidx) => {
    // if the index is not the one we want return the while grup as is
    if (gidx !== gindex) return grup;
    // otherwise create a new one by spreading the existing
    return {
      ...grup,
      // and override the prop which is changed
      components: grup.components.map((component, cidx) => {
        // again if the component is not the one we want to update
        // return it as is
        if (cidx !== cindex) return component;
        // otherwise create a new one by spreading the existing
        // and adding/modifying the props we want
        return {
          ...component,
          tip: 'datetime'
        }
      })
    }
  });

  setGrups(newgrups);
}

如果只想使用已有的代码,则只需创建一个新组件即可。

newgrups[gindex].components[cindex] = { ...newgrups[gindex].components[cindex],
  tip: 'datetime'
}

答案 1 :(得分:0)

设计状态和设计数据库一样是一种好习惯。建议在数据库中使用normalised design,因为您不能仅将状态嵌套在其他状态中。在您的情况下,您可以用相同的方式拆分状态:

[
    {
      id: 1,
      css: "col"
    },

    {
      id: 2,
      css: "col"
    }
];

组件

[
        { grups_id: 1, id: 1, type: "textbox" },
        { grups_id: 1, id: 2, type: "integer" },
        { grups_id: 2, id: 1, type: "numerictextbox" },
        { grups_id: 2, id: 2, type: "dropdown" }
]

这大大简化了处理状态的过程,避免了嵌套和复杂的过程。您可以通过应用componenents.filter()并通过grups_id进行过滤来轻松使用组件。