【发布时间】:2020-04-17 20:27:20
【问题描述】:
我在构建更新助手时遇到问题,想知道是否有人知道如何设置它。我的状态是这样的:
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' }}})
}))
谢谢!
【问题讨论】:
-
为什么在 prevState.array[1] 内部更新之前使用扩展运算符?它以数组源为第一个参数
-
另外拼接上的语法也不正确,它需要一个数组数组来表示要拼接的值
标签: javascript reactjs setstate