我已经修改了用按键选择使用 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!');
}
...
};
我正在设置gridApi
using onGridReady
在按下任何键之前(通过添加确认console.log
)。所以我不知道情况如何undefined
.
我的完整源代码是here.
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
.
-
AgGridReact
在后续的重新渲染中将使用第一个keyboardNavigation
实例,因此参考一样的旧 gridApi
即使现在已经设定了。
您可以通过记录来验证这一点gridApi
在render方法中,你可以从第二个render中看到,它已经被初始化了,而你的closure keyboardNavigation
仍然引用stale的实例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()
}
现场演示
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)