Data Grid - 服务器端树形数据 🧪
使用服务器端数据源的树形数据懒加载。
要从服务器动态加载树形数据,包括子节点的懒加载,您必须创建一个数据源并将 unstable_dataSource
属性传递给 Data Grid,详情请参阅概述部分。
数据源还需要一些额外的属性来处理树形数据
getGroupKey()
: 返回行的分组键。getChildrenCount()
: 返回行的子节点数量。如果由于某种原因子节点数量不可用,但存在一些子节点,则返回-1
。
const customDataSource: GridDataSource = {
getRows: async (params) => {
// Fetch the data from the server.
},
getGroupKey: (row) => {
// Return the group key for the row, e.g. `name`.
return row.name;
},
getChildrenCount: (row) => {
// Return the number of children for the row.
return row.childrenCount;
},
};
与其他参数(如 filterModel
、sortModel
和 paginationModel
)类似,getRows()
回调接收一个 groupKeys
参数,该参数对应于在 getGroupKey()
中为每个嵌套级别提供的键。在服务器上使用 groupKeys
来提取给定嵌套级别的行。
const getRows: async (params) => {
const urlParams = new URLSearchParams({
// Example: JSON.stringify(['Billy Houston', 'Lora Dean']).
groupKeys: JSON.stringify(params.groupKeys),
});
const getRowsResponse = await fetchRows(
// Server should extract the rows for the nested level based on `groupKeys`.
`https://mui.org.cn/x/api/data-grid?${urlParams.toString()}`,
);
return {
rows: getRowsResponse.rows,
rowCount: getRowsResponse.rowCount,
};
}
以下树形数据示例支持服务器端的筛选、排序和分页。默认情况下,它还会缓存数据。
错误处理
对于每个行组展开,都会调用数据源来获取子节点。如果在获取过程中发生错误,网格将在行组单元格中显示错误消息。unstable_onDataSourceError
也会随错误和获取参数一起触发。
下面的演示除了分组单元格中的默认错误消息外,还显示了一个 toast 提示。为了简单起见,此演示中已禁用缓存。
分组展开
分组展开背后的思想与“行分组”部分中解释的相同。不同之处在于,数据最初不可用,并且在 Data Grid 安装后,根据属性 defaultGroupingExpansionDepth
和 isGroupExpandedByDefault
以瀑布方式自动获取。
以下演示使用 defaultGroupingExpansionDepth={-1}
默认展开树的所有级别。
自定义缓存
数据源默认使用缓存来存储获取的数据。如有必要,使用 unstable_dataSourceCache
属性来提供自定义缓存。有关更多信息,请参阅数据缓存。
以下演示使用来自 @tanstack/react-core
的 QueryClient
作为数据源缓存。