在空 ag-grid 中动态添加和删除行,第一次行被删除,第二次抛出错误

Dynamically adding and deleting row in empty ag-grid,first time row is getting deleted, second time throwing error

最初我显示的是带有 header 个名字的空网格。单击添加按钮时,新空行应添加删除 icon.I 我能够动态添加行 ag-grid。第一次如果我在添加后删除行,它会被删除,但第二次它在下面给我错误..

第二次,报错

Uncaught TypeError: Cannot read property 'data' of undefined

调用添加行的方法:-

createNewRowData() {
  let newData = {
    tableName: '',
    schemaName: '',
    columnName: '',
    condition: ''
  };
  console.log('newDATA', newData);
  this.setState({
    newCount:this.state.newCount+1
})
}
onAddRow() {
  let newItem = this.createNewRowData.bind(this);
  let res = this.state.gridOptions.api.updateRowData({add: [newItem]});
}

删除时调用的方法:-

methodFromParent(cell) {
  const rowNode = this.state.gridOptions.api.getRowNode(cell.rowIndex);
  this.state.gridOptions.api.updateRowData({remove: [rowNode.data]});
  this.state.newCount--;
}

我用于删除的自定义单元格渲染器,它出现在我在 colDefs 中使用的每一行中:-

export default class DeleteButtonRenderer extends Component {
  constructor(props) {
    super(props);
    this.invokeParentMethod = this.invokeParentMethod.bind(this);
  }
  invokeParentMethod(e) {
    this.props.context.componentParent.methodFromParent(this.props.node);
  }
  render() {
    return (
      <span>
        <a
          style={{ height: 20, lineHeight: 0.5 }}
          onClick={this.invokeParentMethod}
        >
          <i className="far fa-trash-alt fa-2x" />
        </a>
      </span>
    );
  }
}

因此,方法 methodFromParent(rowIndex) - 有 rowIndex 输入 属性,但它不属于 index,您在此使用 e.target.id方法 .methodFromParent(+e.target.id) - 作为 index - 这就是你遇到问题的原因。

RowNode界面,可以访问rowIndex

/** The index of this node in the grid, only valid if node is displayed in the grid, otherwise it should be ignored as old index may be present */
rowIndex: number;

在自定义渲染器上,您可以访问完整的 node 数据(RowNode 接口),因此只需将 node.rowIndex 传递给 invokeParentMethod 函数即可。

它可能是第一次工作,因为 id 可能与 index 相同,但无论如何要了解更多详细信息,我需要获取您的真实代码,所以如果您是可以,提供plinkr或stackblitz。

Update

所以,我深入研究了你的样本,在这里我发现了:

首先,this.createNewRowData.bind(this)——是一个引用绑定,需要使用implicit,这里不需要,你需要直接执行它(explicit),尝试console.log(newItem)为了清楚 , 你会得到一个 function 参考。

其次,createNewRowData - return 不是一个新对象,当您修复像 let newItem = this.createNewRowData(); 这样的函数执行时,它将是 undefined.

第三,如果您打算在网格中使用 empty 个对象,那么 updateRowData({remove: [rowNode.data]}); 将不起作用,您需要使用不同的方式 remove,例如- selection

自定义渲染器

invokeParentMethod(){
    this.props.node.setSelected(true);
    this.props.context.componentParent.methodFromParent();
}

parent(主网格组件)

methodFromParent(){
    let selectedData = this.gridApi.getSelectedRows();
    this.gridApi.updateRowData({ remove: selectedData });
};

Demo