如何使用当前的MUI状态来对列进行求和并显示?

huangapple go评论86阅读模式
英文:

How do I use the current MUI state to sum and display columns?

问题

我正在创建一个MUI webapp来跟踪一些个人数据。

我正在使用MUI datagrid pro来显示数据,如我们所知,它在datagrid组件内部具有一些相当广泛的过滤器。

我想要显示当前显示的过滤列的总计总数,而不是重新查询数据库以获取这些特定值。这似乎应该是相当简单的,但我不确定如何访问它。

datagridpro的API在这里:https://mui.com/x/api/data-grid/data-grid-pro/

我的datagrid组件构建如下:

const fetchData = useCallback(
  async (IDs: string[]) => {
    response = await fetch("/api/data")
    data = response.json()
    // ...
    // ...
    // ...

    transformedData = transformData(data)

    return { data: transformedData }, };
 [dispatch] );

这通过标准的useEffect来设置数据的状态。

transformedData方法类似于这样:

const transformedData = (data: any) => {
   return data.map((item: any, index: any) => {
  const timestamp = new Date(item.timestamp)

  return {
    id: item.id,
    value_1: item.value_1,
    value_2: item.value_2,
    date: timestamp,
    value_3: item.value_3
   };
});
};

这是当前显示DataGridPro组件的代码:

<DataGridPro
    rows={transformedDataFromFunction}
    sx={{
      ".MuiDataGrid-row:hover": {
        backgroundColor: "#C2C2C2",
      },
    }}
    columns={columns}
    editMode="row"
    rowModesModel={rowModesModel}
    onRowModesModelChange={(newModel: typeof rowModesModel) =>
      setRowModesModel(newModel)
    }
    onRowEditStart={handleRowEditStart}
    onRowEditStop={handleRowEditStop}
    processRowUpdate={processRowUpdate}
    componentsProps={{
      toolbar: { setRowModesModel },
    }}
    slots={{ toolbar: GridToolbar }}

    // leaving this in here on off chance we don't need MUI
    // experimentalFeatures={{ newEditingApi: true }}
  />

再次强调,我基本上想在页面顶部的一个单独的div中显示指定列的总和,格式如下:

总计值1:sum(value_1) | 总计值2:sum(value_2) | 总计数:sum(index)


[插入表格数据在这里]

再次强调,当我根据MUI datagrid进行筛选时,我想要显示这些显示列的总和。

假设value_1总共有4行,下面显示了值

value_1
|   3
|   4
|   1
|   2

假设我想要按>2的值进行筛选。

在datagridpro组件上,这将被筛选并显示为:

value_1
|   3
|   4

我想要显示列的count,这将是2,行的总和将是7

我应该使用哪些API属性来访问这些信息?

谢谢!

英文:

I have an MUI webapp I'm creating to track some personal data.

I am using MUI datagrid pro to display the data, and as we know, it has some pretty extensive filters within the datagrid component.

I would like to display summated totals of the currently displayed filtered columns, rather than having to requery the database to get those specific values. It feels like it should be fairly straightforward, but I'm not sure how to access it.

The datagridpro API is here: https://mui.com/x/api/data-grid/data-grid-pro/

My datagrid component is constructed like so:

const fetchData = useCallback(
    async (IDs: string[]) =&gt; { 
        response = await fetch(&quot;/api/data&quot;)
        data = response.json()
        ...
        ...
        ... 


        transformedData = transformData(data)

        return { data: transformedData }, }; 
     [dispatch] );

This gets fed through a standard useEffect to set the state with the data.

And the transformedData method resembles this:

const transformedData = (data: any) =&gt; {
   return data.map((item: any, index: any) =&gt; {
  const timestamp = new Date(item.timestamp)

  return {
    id: item.id
    value_1: item.value_1
    value_2: item.value_2
    date: timestamp
    value_3: item.value_3
   };
});
};

This is the current code displaying the DataGridPro component:

&lt;DataGridPro
    rows={transformedDataFromFunction}
    sx={{
      &quot;.MuiDataGrid-row:hover&quot;: {
        backgroundColor: &quot;#C2C2C2&quot;,
      },
    }}
    columns={columns}
    editMode=&quot;row&quot;
    rowModesModel={rowModesModel}
    onRowModesModelChange={(newModel: typeof rowModesModel) =&gt;
      setRowModesModel(newModel)
    }
    onRowEditStart={handleRowEditStart}
    onRowEditStop={handleRowEditStop}
    processRowUpdate={processRowUpdate}
    componentsProps={{
      toolbar: { setRowModesModel },
    }}
    slots={{ toolbar: GridToolbar }}

    // leaving this in here on off chance we don&#39;t need MUI
    // experimentalFeatures={{ newEditingApi: true }}
  /&gt;

Again, I essentially want to display the summated totals of specified columns in a separate div at the top of the page, in the form:

Total Val 1: sum(value_1) | Total Val 2: sum(value_2) | Total #: sum(index)


[insert table data here]

Again, when I filter based on the MUI datagrid, I'd like to display the summated totals of those displayed columns.

Let's say value_1 has 4 rows total with values displayed below

    value_1 
   |   3     
   |   4
   |   1
   |   2

Let's say I want to filter by values &gt;2.

On the datagridpro component, this would be filtered and displayed as this:

    value_1 
   |   3     
   |   4

I want to show the count of columns displayed, which would be 2, and the sum of the rows would be 7.

What API prop(s) should I use to access this?

Thank you

答案1

得分: 3

你可以使用MUI DataGridPro API中的gridFilteredSortedRowIdsSelector来获取列的汇总总数。这个选择器返回一个数组,其中包含当前在网格中经过筛选和排序的行标识。您可以使用这个数组来访问行的数据并计算您想要的列的汇总总数。例如,您可以像这样做:

const SummatedTotals = () => {
  const apiRef = useGridApiContext();
  const filteredSortedRowIds = gridFilteredSortedRowIdsSelector(apiRef);

  const filteredSortedRows = filteredSortedRowIds.map((id) =>
    apiRef.current.getRow(id)
  );

  const totalUnitPrice = filteredSortedRows.reduce(
    (sum, row) => sum + row.unitPrice,
    0
  );
  const totalFeeRate = filteredSortedRows.reduce(
    (sum, row) => sum + row.feeRate,
    0
  );
  const totalCount = filteredSortedRows.length;

  return (
    <div>
      {`总单价: ${
        Math.round(totalUnitPrice * 100) / 100
      } | 总费率: ${
        Math.round(totalFeeRate * 100) / 100
      } | 总数: ${totalCount}`}
    </div>
  );
};

然后在DataGridPro组件中使用:

<DataGridPro
  /* { ...restProps } */
  slots={{ footer: SummatedTotals }}
/>

您可以在这里查看完整示例:codesandbox.io

要了解更多信息,请参阅Filtering SelectorsAPI Object访问状态

英文:

You can use the gridFilteredSortedRowIdsSelector from the MUI DataGridPro API to get the summated totals of the columns. This selector returns an array of row ids that are currently filtered and sorted in the grid. You can use this array to access the rows' data and calculate the summated totals of the columns you want. For example, you can do something like this:

const SummatedTotals = () =&gt; {
  const apiRef = useGridApiContext();
  const filteredSortedRowIds = gridFilteredSortedRowIdsSelector(apiRef);

  const filteredSortedRows = filteredSortedRowIds.map((id) =&gt;
    apiRef.current.getRow(id)
  );

  const totalUnitPrice = filteredSortedRows.reduce(
    (sum, row) =&gt; sum + row.unitPrice,
    0
  );
  const totalFeeRate = filteredSortedRows.reduce(
    (sum, row) =&gt; sum + row.feeRate,
    0
  );
  const totalCount = filteredSortedRows.length;

  return (
    &lt;div&gt;
      {`Total Unit Price: ${
        Math.round(totalUnitPrice * 100) / 100
      } | Total Fee Rate: ${
        Math.round(totalFeeRate * 100) / 100
      } | Total #: ${totalCount}`}
    &lt;/div&gt;
  );
};

And then

&lt;DataGridPro
  /* { ...restProps } */
  slots={{ footer: SummatedTotals }}
/&gt;

You can see the whole example here: codesandbox.io

To learn more, please see Filtering Selectors, API Object, and Access The State.

huangapple
  • 本文由 发表于 2023年7月18日 00:16:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/76706358.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定