数据表格 - 服务器端行分组 🧪
使用服务器端数据源进行懒加载行分组。
要从服务器动态加载行分组数据,包括子项的懒加载,请创建一个数据源并将 unstable_dataSource
属性传递给数据表格,如概述部分所述。
与树状数据类似,您需要传递一些额外的属性来启用数据源行分组功能
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;
},
};
除了 groupKeys
之外,getRows()
回调还接收一个 groupFields
参数。这对应于当前的 rowGroupingModel
。在服务器上使用 groupFields
为每个 getRows()
调用分组数据。
const getRows: async (params) => {
const urlParams = new URLSearchParams({
// Example: JSON.stringify(['20th Century Fox', 'James Cameron'])
groupKeys: JSON.stringify(params.groupKeys),
// Example: JSON.stringify(['company', 'director'])
groupFields: JSON.stringify(params.groupFields),
});
const getRowsResponse = await fetchRows(
// Server should group the data based on `groupFields` and
// 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,
};
}
按 Enter 开始编辑
错误处理
如果在 getRows
调用期间发生错误,数据表格会在行分组单元格中显示错误消息。unstable_onDataSourceError
也会被触发,并带有错误和获取参数。
此示例显示了使用 Toast 通知和分组单元格中的默认错误消息的错误处理。为了简单起见,禁用了缓存。
演示
在以下演示中,使用基于 Commodities
数据集自动生成的数据来模拟服务器端行分组。