跳到內容
+

數據網格 - 伺服器端樹狀資料 🧪

具有伺服器端資料來源的樹狀資料延遲載入。

若要從伺服器動態載入樹狀資料,包括子項的延遲載入,您必須建立資料來源,並將 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;
  },
};

與其他參數(例如 filterModelsortModelpaginationModel)一樣,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.dev.org.tw/x/api/data-grid?${urlParams.toString()}`,
  );
  return {
    rows: getRowsResponse.rows,
    rowCount: getRowsResponse.rowCount,
  };
}

以下樹狀資料範例支援伺服器端的篩選、排序和分頁。它預設也會快取資料。

按下 Enter 開始編輯

錯誤處理

對於每個列群組展開,都會呼叫資料來源以擷取子項。如果在擷取期間發生錯誤,網格將在列群組單元格中顯示錯誤訊息。unstable_onDataSourceError 也會與錯誤和擷取參數一起觸發。

下面的示範除了分組單元格中的預設錯誤訊息外,還顯示了快顯訊息。為了簡化起見,在此示範中已停用快取。

群組展開

群組展開背後的概念與列分組章節中解釋的相同。不同之處在於資料最初不可用,並且在數據網格安裝後根據屬性 defaultGroupingExpansionDepthisGroupExpandedByDefault 以瀑布方式自動擷取。

以下示範使用 defaultGroupingExpansionDepth={-1} 預設展開樹狀結構的所有層級。

自訂快取

資料來源預設使用快取來儲存擷取的資料。如有必要,請使用 unstable_dataSourceCache 屬性來提供自訂快取。有關更多資訊,請參閱資料快取

以下示範使用來自 @tanstack/react-coreQueryClient 作為資料來源快取。

按下 Enter 開始編輯