使用不变性助手在特定索引处推送新对象

Push new object at specific index using immutability helper

我试过这样做:

 const rowObj = {key: value};
    const rowIndex = 2;

    this.setState({ 
          data: update(this.state.data, 
              { [rowIndex] : { $push : [rowObj] } }
          ) 
    })

但是,它会抛出这样的错误:

Uncaught Error: update(): expected target of $push to be an array; got undefined.

因为你想推送到一个数组,即数据,你不想指定索引并像这样写

const rowObj = {key: value};

this.setState({ 
      data: update(this.state.data, 
           { $push : [rowObj] } 
      ) 
})

否则如果你想为数组中的特定索引设置一个值,你应该使用$set

const rowObj = {key: value};
const rowIndex = 2;

this.setState({ 
      data: update(this.state.data, 
          { [rowIndex] : { $set : rowObj } }
      ) 
})

这样试试

const rowArray = [{key: value},{key: value},{key: value}];
const obj = {key: value}
const rowIndex = 2;
rowArray.splice(rowIndex, 0, obj);
this.setState({ data: update(this.state.data,{rowArray : {$set : rowArray}} ) });

基于,这里有一个使用不变性助手本身的版本

const rowArray = [{
  key: value
}, {
  key: value
}, {
  key: value
}];
const obj = {
  key: value
}
const rowIndex = 2;
this.setState({
  data: update(this.state.data, {
    rowArray: {
      $splice: [
        [rowIndex, 0, obj]
      ]
    }
  })
});