在数组内部反应更新状态数组

时间:2020-10-02 08:01:39

标签: javascript reactjs

我目前正在尝试在基于React类的组件内部更新状态对象。

问题是我的状态是一个二维数组,看起来像这样:

this.state = {
  items: [
    {
      title: 'first depth',
      items: [
        {
          title: 'second depth',
        },
      ],
    },
  ],
};

要更新状态对象内部数组的第一个深度,请使用以下代码:

this.setState(({items}) => ({
  items: [
    ...items.slice(0, index),
    {
      ...items[index],
      title: 'new Title',
    },
    ...items.slice(index + 1),
  ],
}));

但是我无法更新状态内部数组的第二个深度。

有人知道如何更新第二深度吗?

4 个答案:

答案 0 :(得分:2)

通过传播创建新状态,然后通过拼接更改内部数组:

this.setState((oldState) => {
   const newState = {...oldState}; 
   const newItem = { ...newState.items[index],  title:"new Title"};
   newState.items.splice(index, 1,  newItem);
   return newState;
}

答案 1 :(得分:1)

按照相同的样式,您将需要更改第二深度项目的索引。

this.setState(({items}) => ({
  items: [
    ...items.slice(0, index),
    {
      items: [
        ...items[index].slice(0, indexOf2ndDepth),
        {
          title: 'new Title'
        },
        ...items[index].slice(indexOf2ndDepth + 1),
      ],
      title: 'new Title',
    },
    ...items.slice(index + 1),
  ],
};
}));

这可能会变得非常复杂,我建议您首先隔离第二个深度数组,进行更改,然后将其插入第一个深度数组


this.setState(({ items }) => {
  const secondDepthArray = [
    ...items[index].slice(0, indexOf2ndDepth),
    {
      title: 'new Title',
    },
    ...items[index].slice(indexOf2ndDepth + 1),
  ];

  return {
    items: [
      ...items.slice(0, index),
      {
        items: secondDepthArray
        title: 'new Title',
      },
      ...items.slice(index + 1),
    ],
  };
});

答案 2 :(得分:-1)

为此,您可以将状态存储在变量中,然后使用prev prevState更新阵列来更新阵列

答案 3 :(得分:-1)

您可以从状态克隆新阵列

const newItems = [...this.state.items]
// And then modify it

因此,如果要更新数组,只需setState

this.setState({items: newItems})