首页 > 解决方案 > 使用不变性助手在特定索引处推送新对象

问题描述

我试图这样做:

 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.

标签: reactjsreact-nativeimmutability-helper

解决方案


像这样试试

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

推荐阅读