【问题标题】:React update State Array inside of ArrayReact 更新 Array 内部的 State Array
【发布时间】:2021-01-17 22:15:48
【问题描述】:

我目前正在尝试更新基于 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),
  ],
}));

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

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

【问题讨论】:

  • 您好,您需要一次更新所有元素吗?如果没有,您可以只获取第二个深层项目,更新其内容,然后更新主数组

标签: javascript reactjs


【解决方案1】:

为此,您可以将状态存储在变量中,然后使用 prev prevState 更新您的数组状态

【讨论】:

    【解决方案2】:

    您可以从状态中克隆新数组

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

    所以如果你想更新数组只需 setState

    this.setState({items: newItems})
    

    【讨论】:

    • Spread 是一个浅克隆,你需要克隆每个嵌套数组来回答 ops 问题。
    【解决方案3】:

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

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

    【讨论】:

      【解决方案4】:

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

      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),
          ],
        };
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-08-14
        • 2015-05-27
        • 2022-12-28
        • 1970-01-01
        • 2015-05-04
        • 2019-01-12
        • 2022-12-27
        相关资源
        最近更新 更多