You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在MUI Datagrid中忽略‘TOTAL’行的排序?

解决MUI X Data Grid中「TOTAL」行不受排序影响的问题

直接修改Data Grid内部状态的做法不可取,不仅容易引发状态不一致,硬编码行ID的方式也完全不具备扩展性。下面给你两种更可靠的实现方式:

方式一:通过受控数据源手动拼接汇总行

把普通数据行和「TOTAL」汇总行分开处理,排序只作用于普通数据,最后再把汇总行追加到末尾:

// 假设你的原始数据是data,汇总行是totalRow
const [sortModel, setSortModel] = useState([]);
const [displayRows, setDisplayRows] = useState([...data, totalRow]);

const handleSortModelChange = (newSortModel) => {
  setSortModel(newSortModel);
  
  if (newSortModel.length === 0) {
    // 无排序时直接拼接
    setDisplayRows([...data, totalRow]);
    return;
  }

  const { field, sort } = newSortModel[0];
  // 仅对普通数据行排序
  const sortedData = [...data].sort((a, b) => {
    if (sort === 'asc') {
      return a[field] > b[field] ? 1 : -1;
    }
    return a[field] < b[field] ? 1 : -1;
  });
  // 把汇总行固定在最后
  setDisplayRows([...sortedData, totalRow]);
};

然后在Data Grid中使用受控的displayRows和sortModel:

<DataGrid
  rows={displayRows}
  columns={columns}
  sortModel={sortModel}
  onSortModelChange={handleSortModelChange}
/>

方式二:自定义排序比较器

通过sortComparator属性,在排序逻辑中直接把汇总行固定到末尾:

// 假设汇总行的id标记为'total'
const customSortComparator = (a, b, field, direction) => {
  // 把汇总行固定在最后
  if (a.id === 'total') return 1;
  if (b.id === 'total') return -1;
  
  // 常规排序逻辑
  if (direction === 'asc') {
    return a[field] > b[field] ? 1 : -1;
  }
  return a[field] < b[field] ? 1 : -1;
};

在Data Grid中配置这个比较器:

<DataGrid
  rows={rows} // 这里包含普通行和汇总行
  columns={columns}
  sortComparator={customSortComparator}
/>

这两种方式都能稳定实现「TOTAL」行不受排序影响的需求,避免直接操作组件内部状态带来的潜在问题。

内容的提问来源于stack exchange,提问作者Павел Топский

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 13:05:55