資料網格 - 伺服器端資料列分組 🧪
使用伺服器端資料來源的延遲載入資料列分組。
若要從伺服器動態載入資料列分組資料 (包含子項目的延遲載入),請建立資料來源,並將 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.dev.org.tw/x/api/data-grid?${urlParams.toString()}`,
);
return {
rows: getRowsResponse.rows,
rowCount: getRowsResponse.rowCount,
};
}
按下 Enter 鍵開始編輯
錯誤處理
如果在 getRows
呼叫期間發生錯誤,資料網格會在資料列群組儲存格中顯示錯誤訊息。unstable_onDataSourceError
也會隨著錯誤和提取參數觸發。
此範例顯示使用快顯通知和分組儲存格中的預設錯誤訊息進行錯誤處理。為了簡化,快取已停用。
群組展開
群組展開的工作方式與資料來源樹狀資料類似。以下示範使用 defaultGroupingExpansionDepth={-1}
展開所有群組。
示範
在以下示範中,使用根據「商品」資料集自動產生的資料來模擬伺服器端資料列分組。