SuperAPI AI 工具集

sorting

前端与建站

查看项目

更新于 10-16 04:03

技能介绍

用途

这是一个针对 TanStack Table 行排序功能的技能,用于配置和实现表格列的排序行为。资料指出,该技能建立在 core、table-features 和 client-vs-server 三个基础技能之上。其核心概念是:排序状态只描述顺序;客户端处理需要 sorted model,服务端处理需要输入本身已排序。

主要能力

  • 通过 rowSortingFeature 与 createSortedRowModel() 启用行排序与客户端排序模型。
  • 通过 sortFns 注册内置比较器,如 sortFn_alphanumeric、sortFn_text。
  • 支持多列排序(enableMultiSort)与排序移除(enableSortingRemoval)。
  • 支持未定义值放置策略(sortUndefined)。
  • 支持手动/服务端排序模式(manualSorting)。
  • 支持为列指定按字符串名称引用的比较器,或使用 sortFn: 'auto' 自动解析。

使用方式

资料给出的设置示例(保持原样):

import {
  createSortedRowModel,
  rowSortingFeature,
  sortFn_alphanumeric,
  sortFn_text,
  tableFeatures,
} from '@tanstack/table-core'

export const features = tableFeatures({
  rowSortingFeature,
  sortedRowModel: createSortedRowModel(),
  sortFns: { alphanumeric: sortFn_alphanumeric, text: sortFn_text },
})

核心配置示例(保持原样):

const options = { enableSortingRemoval: false, enableMultiSort: true }
const numericColumn = { sortUndefined: 'last' as const }

资料建议导入单个 sortFn_* 内置比较器,只注册列通过字符串名称引用的、或 sortFn: 'auto' 针对自身数据类型需要解析的那些。完整的 sortFns 注册表对象仍然可用,但会打包所有内置比较器;数值列在未注册时会回退到基础比较器。可通过 node_modules/@tanstack/table-core/dist/features/row-sorting/ 与 dist/features/row-sorting/sortFns.d.ts 查看当前名称与比较器契约。

常见错误(资料原文要点)

  • [CRITICAL] 期望 manual 模式重新排序。错误写法:const options = { data: unsortedRows, manualSorting: true };正确写法:const options = { data: serverSortedRows, manualSorting: true }。手动排序会绕过 sortedRowModel,直接信任传入顺序。来源:packages/table-core/src/features/row-sorting/rowSortingFeature.types.ts。
  • [HIGH] 在比较器内部反向。错误写法:const newest: SortFn<any, any> = (a, b, id) => b.getValue<number>(id) - a.getValue<number>(id);正确写法:const numeric: SortFn<any, any> = (a, b, id) => a.getValue<number>(id) - b.getValue<number>(id)。只返回升序比较结果,降序时由 Table 负责反向。来源:docs/framework/react/guide/sorting.md#custom-sorting-functions。
  • [MEDIUM] 排序策略含义不清。错误写法:const options = { enableSortingRemoval: true };正确写法:const options = { enableSortingRemoval: false }; const rankColumn = { sortUndefined: 'last' as const }。除非显式配置,未定义值放置与移除循环可能与预期产品行为不一致。来源:packages/table-core/src/features/row-sorting/rowSortingFeature.types.ts。

适用场景

适用于为表格实现客户端排序、服务端/手动排序、多列排序与自定义比较器的场景,尤其是需要对未定义值位置、排序循环与比较器方向进行明确控制的表格产品。

限制

资料未提供收费、价格、平台支持范围或具体效果等说明。该技能的完整依赖前提(core、table-features、client-vs-server)为资料明确提及;其余未在资料中出现的功能与限制暂未提供。