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

Javascript 在数组内部反应更新状态数组,javascript,reactjs,Javascript,Reactjs,我目前正在尝试更新基于react类的组件中的状态对象 问题是我的状态是一个二维数组,如下所示: this.state = { items: [ { title: 'first depth', items: [ { title: 'second depth', }, ], }, ], }; 为了更新状态对象中数组的第一个深度,我使用以下代码: this.setState(({items

我目前正在尝试更新基于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),
  ],
}));
但是我无法在我的状态内更新数组的第二个深度


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

要做到这一点,您可以将状态存储在变量中,然后更新数组。使用prev prevState更新状态您的数组可以从状态克隆新数组

const newItems = [...this.state.items]
// And then modify it
所以,如果您想更新数组,只需设置state

this.setState({items: newItems})

通过排列创建新状态,然后通过拼接更改内部阵列:

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

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

this.setState(({items})=>({
项目:[
…items.slice(0,索引),
{
项目:[
…项[索引]。切片(0,indexOf2ndDepth),
{
标题:“新标题”
},
…项[index].切片(indexOf2ndDepth+1),
],
标题:“新标题”,
},
…项。切片(索引+1),
],
};
}));
这可能会变得非常复杂,我建议您首先隔离第二个深度数组,进行更改,然后将其插入第一个深度数组


this.setState(({items})=>{
第二个德布雷常数=[
…项[索引]。切片(0,indexOf2ndDepth),
{
标题:“新标题”,
},
…项[index].切片(indexOf2ndDepth+1),
];
返回{
项目:[
…items.slice(0,索引),
{
项目:第二次德布雷
标题:“新标题”,
},
…项。切片(索引+1),
],
};
});

Hi,是否需要一次更新所有元素?如果没有,您可以只获取第二个深层项,更新其内容,然后更新主阵列。如果展开是浅层克隆,则还需要克隆每个嵌套阵列以回答ops问题。