2016-08-24 91 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是工作在陣列的長度內