我正在使用 ag-grid React 并尝试使用 api 更新数据:
rowNode.setData()
但是当我尝试读取 rowData 时它没有改变......
我的代码:
import { AgGridReact } from 'ag-grid-react'; // AG Grid Component
import "ag-grid-community/styles/ag-grid.css"; // Mandatory CSS required by the grid
import "ag-grid-community/styles/ag-theme-quartz.css"; // Optional Theme applied to the grid
import { useRef, useState } from 'react';
import { ColDef } from 'ag-grid-community';
const GridExample = () => {
// Row Data: The data to be displayed.
const [rowData, setRowData] = useState([
{ make: "Tesla", model: "Model Y", price: 64950, electric: true, id: '1' },
{ make: "Ford", model: "F-Series", price: 33850, electric: false, id: '2' },
{ make: "Toyota", model: "Corolla", price: 29600, electric: false, id: '3' },
]);
// Column Definitions: Defines the columns to be displayed.
const [colDefs, setColDefs] = useState<ColDef[]>([
{ field: "make", editable: true },
{ field: "model" },
{ field: "price", },
{ field: "electric" }
]);
const gridRef = useRef<AgGridReact>()
return (
// wrapping container with theme & size
<div
className="ag-theme-quartz" // applying the grid theme
style={{ height: 500 }} // the grid will fill the size of the parent container
>
<AgGridReact
ref={gridRef}
rowData={rowData}
columnDefs={colDefs}
getRowId={({ data }) => data.id}
/>
<button onClick={() => {
console.log('rowData', rowData);
}}>print data</button>
<button onClick={() => {
const rowNode = gridRef.current?.api.getRowNode('2')
//This is the row update
rowNode?.setData( { make: "Ford", model: "newModel", price: 33850, electric: false, id: '2' });
}}>update data</button>
</div>
)
}
const App = () => {
return <GridExample />
}
export default App
我采用了 ag-grid 的代码示例并添加了 rowId 和按钮。
因此,当我单击更新数据按钮时,表格上的数据会发生变化,但当我打印数据时,它仍然像以前一样。
我尝试使用
api.applyTransaction()
和 rowNode.updateData()
但结果相同...
由于某种原因, rowNode.setDataValue 将更新 rowNode 但我无法在我的项目中使用它,因为它没有支持对象。
您应该知道,如果网格数据内部更改,AG-Grid 不会更新您的本地状态。
您应该使用声明式方法(传递 rowData 属性并更新属性 -> setRowData)或使用命令式方法(使用 grid api 对象并手动设置数据)