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

Sag*_*ada 5 reactjs react-native immutability-helper

我尝试这样做:

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

    this.setState({ 
          data: update(this.state.data, 
              { [rowIndex] : { $push : [rowObj] } }
          ) 
    })
Run Code Online (Sandbox Code Playgroud)

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

Uncaught Error: update(): expected target of $push to be an array; got undefined.
Run Code Online (Sandbox Code Playgroud)

小智 2

尝试这样

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}} ) });
Run Code Online (Sandbox Code Playgroud)