I'm using AG-Grid to build an react application to display data from an api like a spreadsheet. Getting the data and showing it works fine, know I want to edit the data, or change the value with a predefined list, which is also fetched through an api.
This is where I'm stuck since yesterday and I can't figure it out. Here is some example code:
import React, { Component } from 'react';
import { AgGridReact } from 'ag-grid-react';
class AgGridExample extends Component {
constructor(props) {
super(props);
this.state = {
rowData: [],
selectData: []
};
}
columnDefs = [
{
headerName: "MyListData", field: "item", editable: true, cellEditor: "agSelectCellEditor",
cellEditorParams: function () { // cellEditorParams: {values: ["1", "2"]}
return {
values: this.state.selectData
}
}
},
{ headerName: "value", field: "value", editable: true },
];
/**
* fetch all necessary data from data sources
*/
componentDidMount() {
fetch('http://localhost:5000/api/rowdata')
.then(result => result.json())
.then(rowData => this.setState({ rowData }))
fetch('http://localhost:5000/api/selectdata')
.then(result => result.json())
.then(selectData => this.setState({ selectData }))
};
render() {
return (
<AgGridReact
enableSorting={true}
enableFilter={true}
rowData={this.state.rowData}
columnDefs={this.columnDefs}>
</AgGridReact>
);
};
}
export default AgGridExample;
The Data:
rowData: [{"value": "a", "item":"1"}, {"value": "b", "item":"2"}]
selectData: ["1", "2"]
Now I'm new with react and as far as I understood, the best place to fetch the data from an external source is in componentDidMount and updating the state. I did some reading, and the problem seems to be, that it is rendered, before the data is fetched, or the state could be updated. I tried with componentWillMount, but I got the same error, when I try to edit the field:
TypeError: Cannot read property 'state' of undefined
What would be the best practice to tackle this problem?
Thanks in advance for any help, hints, examples.
答案 0 :(得分:1)
您的问题似乎更像是Javascript问题,而不是与ag-grid有关的任何事情。
返回对象内部的this
对全局定义的状态变量一无所知
您有两种将动态值传递到单元格编辑器的方法。
解决方案1:
摆脱cellEditorParams
中的函数,然后使用类似的功能-
cellEditorParams: {
values: this.state.selectData
}
解决方案2:
如果仍要为cellEditorParams
使用一个函数,则可以将函数分离出来,并使用bind
传递上下文,如下所示。
testVals() {
return {
values : this.state.selectData
}
}
在您的colDef中-
{
headerName: "MyListData",
field: "item",
editable: true,
cellEditor: "agSelectCellEditor",
cellEditorParams: this.testVals.bind(this)
}
来自docs
的示例