Material UI DataGrid服务端分页下如何持久化selectionModel状态
解决Material UI DataGrid服务端分页下选中状态持久化问题
服务端分页模式下,切换页面时DataGrid会因当前行数据更新自动清空selectionModel,要实现选中状态持久化,需手动维护全局选中ID集合,而非直接用组件返回的选中值覆盖状态,具体实现如下:
维护全局选中ID集合
定义全局数组存储所有页面的选中行ID,替代直接覆盖的状态更新方式。修改选中事件处理逻辑
在onSelectionModelChange中,对比当前页行ID与全局选中集合,判断新增或移除的ID,更新全局集合。传递过滤后的选中状态到DataGrid
给DataGrid的selectionModel传入当前页存在的已选中ID,确保当前页正确显示勾选状态。
完整代码示例
// 状态定义 const [selectedRowIds, setSelectedRowIds] = useState([]); const [currentPageRows, setCurrentPageRows] = useState([]); // 对应原代码的row状态 const [totalCount, setTotalCount] = useState(0); const [loading, setLoading] = useState(false); // 分页变更处理(原handlePaginationModelChange逻辑) const handlePaginationModelChange = async (model) => { setLoading(true); // 调用接口获取当前页数据 const res = await fetchYourDataApi(model.page, model.pageSize); setCurrentPageRows(res.rows); setTotalCount(res.total); setLoading(false); }; // 选中状态变更处理 const handleSelectionModelChange = (newSelection) => { // 获取当前页所有行的ID const currentPageRowIds = currentPageRows.map(row => row.didId); // 筛选本次新增的选中ID const newlySelected = newSelection.filter(id => !selectedRowIds.includes(id)); // 筛选本次取消选中的ID const unselected = selectedRowIds.filter(id => currentPageRowIds.includes(id) && !newSelection.includes(id)); // 更新全局选中集合 setSelectedRowIds(prev => [ ...prev.filter(id => !unselected.includes(id)), ...newlySelected ]); }; // DataGrid组件 <CustomizedDataGrid rows={currentPageRows} loading={loading} columns={didColoumn} autoWidth={true} scrollbarSize={10} rowCount={totalCount} autoHeight={true} getRowId={(row) => row.didId} disableColumnMenu pageSizeOptions={[5, 10, 25, 50, 100]} disableRowSelectionOnClick onPaginationModelChange={handlePaginationModelChange} checkboxSelection onSelectionModelChange={handleSelectionModelChange} // 传递当前页已选中的ID,确保页面显示正确勾选状态 selectionModel={selectedRowIds.filter(id => currentPageRows.some(row => row.didId === id))} paginationMode="server" pagination pageSize={5} slots={{ pagination: CustomPagination, columnUnsortedIcon: CustomUnsortedIcon, }} localeText={{ noRowsLabel: 'No Data Found' }} />
关键说明
- 全局
selectedRowIds存储所有页面的选中行ID,切换页面时不会被重置。 - 每次页面切换后,
selectionModel过滤出当前页存在的已选中ID,保证DataGrid正确显示勾选状态。 - 全选/取消全选当前页时,逻辑会自动批量添加/移除当前页的行ID到全局集合。
内容的提问来源于stack exchange,提问作者Adarsh Pandey
相关产品推荐
相关产品推荐

