我有一个来自 MUI 的数据网格,如下所示:
<DataGrid
apiRef={apiRef}
experimentalFeatures={{ newEditingApi: true }}
headerHeight={23}
showCellRightBorder
showColumnRightBorder
disableColumnMenu
onColumnHeaderClick={(params: GridColumnHeaderParams) => {
setSelectedColumn(params.colDef.field);
}}
columns={formattedColumnsToShow}
rows={timeSheetFees || []}
rowHeight={29}
onCellClick={(_params, event) => {
event.defaultMuiPrevented = true;
}}
processRowUpdate={handleProcessRowUpdate}
onProcessRowUpdateError={handleProcessRowUpdateError}
throttleRowsMs={1000}
/>
传入 processRowUpdate 的函数只是更新本地状态(没有后端 API 调用):
const handleProcessRowUpdate = useCallback(
(newRow: MappedTableEntryRowType) => {
return processRowUpdate(newRow);
},
[processRowUpdate]);
我有这个 useEffect ,我试图更新一行(一行内 3 个不同的单元格):
useEffect(() => {
const updateCurrentCell = async (id: string, field: string, value: string | undefined) => {
await apiRef.current.setEditCellValue({ id, field, value });
apiRef.current.stopCellEditMode({ id, field });
};
if (!isEmpty(selectedMatterFromModal)) {
const id = selectedRow;
const { matterId } = selectedMatterFromModal;
const { field } = selectedCell;
updateCurrentCell(id, field, matterId);
apiRef.current.updateRows([{ id, matterNo: matterId, matterId, matterDescription: matterId, client: matterId }]);
setSelectedMatterFromModal({});
}
}, [apiRef, selectedCell, selectedMatterFromModal, selectedRow, setSelectedMatterFromModal]);
但是每次调用 processRowUpdate 时,都会传入旧行数据,从而覆盖我刚刚更新的任何新值。我必须使用 useEffect,因为新行值附带的数据位于 DataGrid 上下文之外,因此我无法使用内置回调或任何其他内容来实现此目的。
我该如何解决这个问题?
我有同样的问题,似乎 newRow 和 oldRow 值在数据网格 processRowUpdate 中颠倒了。可能是一个错误。
在等待知道确切的解决方案时,我实施了以下解决方法
这是我的问题和解决方法:
//In my custom field : i create the newRow values when user click on submit
const updateRows = (selectedOptions) => {
let oldRow=props.params.row;
let newRow={...oldRow};
newRow[props.params.colDef.field]=selectedOptions;
//My workaround here : in a "homemade cache" I store a variable indicating that the updateRows api is currently in use
Common.setCache("api.updateRows.used",true);
props.params.api.updateRows([newRow]);
}
当执行上述 api.updaterows api 时,也会执行 datagrid processRowUpdate。在这里我看到了和你一样的问题,newRow 不是正确的!而是传递了oldRow。但旧的 Row 变量包含正确的 newRow 数据。所以价值观好像颠倒了
因此,我在 Datagrid 组件中实现了以下解决方法:
const processRowUpdate = (newRow, oldRow,isNew) => {
//I use a homemade cache to store information if I use the API or not. If yes, I re-invert the data to have them in the right variables
if(Common.getCache("api.updateRows.used").data) {
let prevNewRow={...newRow};
newRow={...oldRow};
oldRow={...prevNewRow};
Common.setCache("api.updateRows.used",false);
}
它可以工作,但不干净。我想知道是否可以只使用API