gpt4 book ai didi

reactjs - React 插件更新 - 如何将对象插入到对象数组中?

转载 作者:行者123 更新时间:2023-12-04 02:10:24 25 4
gpt4 key购买 nike

我有一个由 this.state.blocks 表示的对象数组。如何将新对象插入此数组中的 pos 位置?这是我到目前为止所拥有的,但我收到了错误

Error: update(): expected target of $push to be an array; got [object Object].

let newBlocks = update(this.state, {
blocks: {
[pos] : {$push: [obj]}
}
});
this.setState({
blocks: newBlocks
});

最佳答案

$push 将元素追加到数组的末尾,您需要 $splice这里:

this.setState({
blocks: update(this.state.blocks, {$splice: [[pos, 0, obj]]})
})

将在 pos 指定的索引处将 obj 插入到 this.state.blocks 中(首先删除 0 个项目)。splice 根据规范工作:

startIndex: index at which to start changing the array (with origin 0). If greater than the length of the array, actual starting index will be set to the length of the array. If negative, will begin that many elements from the end.

所以只要 startIndex 在数组的长度内,它就可以正常工作

关于reactjs - React 插件更新 - 如何将对象插入到对象数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39128745/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com