正在使用setState更新不变性助手将对象拼接到处于状态的数组中



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

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);

现在有了不变性助手,当我尝试用索引位置更新prevState.array时,我得到了一个错误,即prevState.array是不可迭代的。有什么想法吗?

我的setState函数看起来像:

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

谢谢!

我不确定这是否是您想要做的,因为您的setState示例似乎使用了与原始.splice不同的值。但我用你的原始拼接作为例子:

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

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
]

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

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)

最新更新