2016-08-24 81 views
1

我有一个由this.state.blocks表示的对象数组。如何在pos的位置插入一个新对象到这个数组中?这是我到目前为止,但我得到的错误React插件更新 - 如何将对象插入到对象数组中?

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

回答

1

$push附加元素(S)到数组的结尾,你需要$splice这里:

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

会在pos指定的索引处插入objthis.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是工作在阵列的长度内