问题
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.
回答1:
Your problem seems more like a Javascript problem than anything to do with ag-grid.
The this
inside return object does not know anything about state variable defined globally
You have 2 ways to pass the dynamic values to your cell editor.
Solution 1:
Get rid of the function in cellEditorParams
and use it something like this -
cellEditorParams: {
values: this.state.selectData
}
Solution 2:
If you still want to use a function for cellEditorParams
, you can separate out the function and pass the context using bind
something like this.
testVals() {
return {
values : this.state.selectData
}
}
And in your colDef -
{
headerName: "MyListData",
field: "item",
editable: true,
cellEditor: "agSelectCellEditor",
cellEditorParams: this.testVals.bind(this)
}
Example from docs
来源:https://stackoverflow.com/questions/53850355/react-and-ag-grid-populating-selectcelleditor-through-fetch-gives-state-of-un