簡體   English   中英

ag-Grid React 在設置 gridApi 后忘記了它

[英]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()
}

現場演示

編輯 64071586/ag-grid-react-forgets-gridapi-after-it-has-been-set

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM