英文:
AgGrid Unable To Restore Original Grid Data
问题
我在初始 API 调用后填充了网格。其中一个字段是可编辑的 - 价格
如果我编辑一个价格单元格,然后点击还原按钮,原始数据集会被应用。
如果我再次编辑一个价格单元格,还原功能将不再起作用。
示例:https://stackblitz.com/edit/ag-grid-react-hello-world-agjiy2?file=index.js
代码:
英文:
I populate the grid after an intial API call. One of the fields is editiable - Price
If i edit a Price cell, and click the Restore button, the original dataset is applied.
If i edit a Price cell again, the Restore no longer works.
Example: https://stackblitz.com/edit/ag-grid-react-hello-world-agjiy2?file=index.js
Code:
import React, { useState, useEffect, useRef } from 'react';
import { render } from 'react-dom';
import { AgGridReact } from 'ag-grid-react';
import 'ag-grid-community/styles/ag-grid.css';
import 'ag-grid-community/styles/ag-theme-alpine.css';
const myPromise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve(
[
{ make: 'Toyota', model: 'Celica', price: 35000 },
{ make: 'Ford', model: 'Mondeo', price: 32000 },
{ make: 'Porsche', model: 'Boxter', price: 72000 },
]
);
}, 300);
});
const App = () => {
const [rowData, setRowData] = useState([]);
const initData = useRef([]);
const [columnDefs] = useState([
{ field: 'make' },
{ field: 'model' },
{ field: 'price', editable: true },
]);
useEffect(() => {
let data = myPromise
.then((data) => {
console.log(data);
setRowData(data);
initData.current = JSON.parse(JSON.stringify(data));
});
}, []);
const restore = () => {
setRowData(initData.current);
}
return (
<div>
<button onClick={restore}>Back to original</button>
<br></br>
<div className="ag-theme-alpine" style={{ height: 400, width: 600 }}>
<AgGridReact rowData={rowData} columnDefs={columnDefs}></AgGridReact>
</div>
</div>
);
};
答案1
得分: 1
更改您的恢复方法如下:
```javascript
const restore = () => {
console.log('initData', initData)
var obj = JSON.parse(JSON.stringify(initData.current))
setRowData(obj);
}
这是因为您在编辑操作之后修改了对象。为了防止它被修改,获取您的initData对象的深拷贝并使用它。
示例代码:
https://stackblitz.com/edit/ag-grid-react-hello-world-fnxqdy?file=index.js
<details>
<summary>英文:</summary>
Change your restore method like that
const restore = () => {
console.log('initData', initData)
var obj = JSON.parse(JSON.stringify(initData.current))
setRowData(obj);
}
It's happening because you modify your object after your edit action. To prevent it modifying, get a deep copy of your initData object and use it.
Playground:
[https://stackblitz.com/edit/ag-grid-react-hello-world-fnxqdy?file=index.js][1]
[1]: https://stackblitz.com/edit/ag-grid-react-hello-world-fnxqdy?file=index.js
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论