使用 setState update immutability helper 将对象拼接成状态数组

Splicing object into array in state with setState update immutability helper

我在构建我的更新助手时遇到问题,想知道是否有人知道如何设置它。我的状态是这样的:

state = {
        array: [
            {
                1: { thing1: 'thing1', thing2: 'thing2' },
            },
            {
                2: { thing1: 'thing1', thing2: 'thing2' },
            },
            {
                3: { thing1: 'thing1', thing2: 'thing2' },
            }
        ]
};

我想获取一个对象并用它替换数组中的特定位置。所以传统上看起来像:

const newObj = {
     newthing1: 'newthing1',
     newthing2: 'newthing2'
};

state.array.splice(0, 1, newObj);

现在使用 immutability-helper,当我尝试使用索引位置更新它时,出现 prevState.array 不可迭代的错误。有什么想法吗?

我的 setState 函数类似于:

this.setState((prevState) => ({
                array: update(...prevState.array[1], {$splice: { 2: { newthing1: 'newthing1' }}})
            }))

谢谢!

为什么不直接使用本地方法。

state = {
  array: [
      {
          1: { thing1: 'thing1', thing2: 'thing2' },
      },
      {
          2: { thing1: 'thing1', thing2: 'thing2' },
      },
      {
          3: { thing1: 'thing1', thing2: 'thing2' },
      }
  ]
};
const newObj = {
  newthing1: 'newthing1',
  newthing2: 'newthing2'
};
const index = 1 // could be any id

const newState = {array: state.array.slice(0, index).concat({[index]: newObj}).concat(state.array.slice(index+1))}
console.log(newState)

我不确定这是否是您想要做的,因为您的 setState 示例看起来使用的值与原始 .splice 不同。但是我以你原来的拼接为例去掉了:

供参考:https://reactjs.org/docs/update.html#nested-collections

    state = {
            array: [
                {
                    1: { thing1: 'thing1', thing2: 'thing2' },
                },
                {
                    2: { thing1: 'thing1', thing2: 'thing2' },
                },
                {
                    3: { thing1: 'thing1', thing2: 'thing2' },
                }
            ]
    };

    const newObj = {
      newthing1: 'newthing1',
      newthing2: 'newthing2'
    };
    this.setState( prevState =>
      update(prevState, { array: { $splice: [[0, 1, newObj]] } })
    );

老实说,这看起来不对,因为对象不一致。我猜你的意思是:

update(prevState, { array: { $splice: [[0, 1, {1: newObj}]] } })

或者如果我放弃了你在 update 的尝试,也许是这个?:

update(prevState, { array: { $splice: [[1, 1, {2: newObj}]] } })

解释它的作用:
prevState 个对象开始,
首先遍历属性array
然后它遍历 splice 命令列表(本例中只有 1 个)
执行这个拼接:

 [
   1, // starting index to splice at
   1, // length to splice out
   {2: newObj} // object(s) to insert
 ]