[英]ag-Grid React forgets gridApi after it has been set
我已經修改了帶有鍵的選擇示例以與 React 一起使用。 但是,只要我按下箭頭鍵,應用程序就會在下面的代碼中崩潰:
const [gridApi, setGridApi] = useState<GridApi | undefined>();
const handleGridReady = (event: GridReadyEvent) => {
setGridApi(event.api);
setGridColumnApi(event.columnApi);
};
const keyboardNavigation = (params: NavigateToNextCellParams): CellPosition => {
if (gridApi === undefined) {
throw new Error('This should never happen!');
}
...
};
我在按下任何鍵之前使用onGridReady
設置gridApi
(通過添加console.log
確認)。 所以我不知道它是如何變得undefined
。
我的完整源代碼在這里。
const [gridApi, setGridApi] = React.useState<GridApi | undefined>();
const onGridReady = (params: GridReadyEvent) => {
setGridApi(params.api);
setGridColumnApi(params.columnApi);
};
console.log(gridApi); // log the latest gridApi instance if re-render
const keyboardNavigation = (
params: NavigateToNextCellParams
): CellPosition => {
// always reference the first instance of gridApi
if (gridApi === undefined) {
throw new Error("This should always happen!");
}
...
}
這通常稱為反應鈎子中的陳舊閉包。 根據我的理解,這里會發生什么:
keyboardNavigation
僅在第一次渲染時注冊一次。keyboardNavigation
gridApi
undefined
第一個渲染中引用了gridApi
實例。AgGridReact
在隨后的重新渲染中將使用第一個keyboardNavigation
實例,因此即使現在已經設置,也會引用相同的舊gridApi
。 您可以通過在 render 方法中記錄gridApi
來驗證,您可以從第二次渲染中看到,它已被初始化,而您的閉包keyboardNavigation
仍然引用了gridApi
的陳舊實例。
為了解決這個問題,您可以更改上面的代碼以使用引用而不是在閉包中烘焙后無法更改的變量。
type AgGridApi = {
grid?: GridApi;
column?: ColumnApi;
};
...
const apiRef = React.useRef<AgGridApi>({
grid: undefined,
column: undefined
});
const api = apiRef.current;
const onGridReady = (params: GridReadyEvent) => {
apiRef.current.grid = params.api;
apiRef.current.column = params.columnApi;
};
const yourCallback = () => {
api.grid?.doSomething()
api.column?.doSomething()
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.