TanStack Table 具有一个简单的底层内部状态管理系统,用于存储和管理表格的状态。它还允许您选择性地提取任何需要在您自己的状态管理中管理的状态。本指南将引导您了解与表格状态交互和管理的不同方式。
您无需进行任何特殊设置即可使表格状态正常工作。如果您在 state
、initialState
或任何 on[State]Change
表格选项中未传入任何内容,表格将会在内部管理其自身的状态。您可以使用 table.getState()
表格实例 API 访问此内部状态的任何部分。
table = createAngularTable(() => ({
columns: this.columns,
data: this.data(),
//...
}))
someHandler() {
console.log(this.table.getState()) //access the entire internal state
console.log(this.table.getState().rowSelection) //access just the row selection state
}
table = createAngularTable(() => ({
columns: this.columns,
data: this.data(),
//...
}))
someHandler() {
console.log(this.table.getState()) //access the entire internal state
console.log(this.table.getState().rowSelection) //access just the row selection state
}
如果您只需要为某些状态自定义其初始默认值,您仍然不需要自己管理任何状态。您只需在表格实例的 initialState
选项中设置值即可。
table = createAngularTable(() => ({
columns: this.columns,
data: this.data(),
initialState: {
columnOrder: ['age', 'firstName', 'lastName'], //customize the initial column order
columnVisibility: {
id: false //hide the id column by default
},
expanded: true, //expand all rows by default
sorting: [
{
id: 'age',
desc: true //sort by age in descending order by default
}
]
},
//...
}))
table = createAngularTable(() => ({
columns: this.columns,
data: this.data(),
initialState: {
columnOrder: ['age', 'firstName', 'lastName'], //customize the initial column order
columnVisibility: {
id: false //hide the id column by default
},
expanded: true, //expand all rows by default
sorting: [
{
id: 'age',
desc: true //sort by age in descending order by default
}
]
},
//...
}))
注意:仅在
initialState
或state
中指定每个特定状态,但不要同时指定两者。如果您将特定的状态值同时传递给initialState
和state
,则state
中初始化的状态将覆盖initialState
中的任何对应值。
如果您需要在应用程序的其他区域轻松访问表格状态,TanStack Table 可以轻松地在您自己的状态管理系统中控制和管理任何或所有表格状态。您可以通过将您自己的状态和状态管理函数传递给 state
和 on[State]Change
表格选项来做到这一点。
您可以仅控制您需要轻松访问的状态。如果您不需要,则 *不必* 控制所有表格状态。建议仅在具体情况下控制您需要的状态。
为了控制特定状态,您需要将相应的 state
值和 on[State]Change
函数都传递给表格实例。
让我们以“手动”服务器端数据获取场景中的过滤、排序和分页为例。您可以将过滤、排序和分页状态存储在您自己的状态管理中,但如果您的 API 不关心这些值,则可以忽略任何其他状态,例如列顺序、列可见性等。
import {signal} from '@angular/core';
import {SortingState, ColumnFiltersState, PaginationState} from '@tanstack/angular-table'
import {toObservable} from "@angular/core/rxjs-interop";
import {combineLatest, switchMap} from 'rxjs';
class TableComponent {
readonly columnFilters = signal<ColumnFiltersState>([]) //no default filters
readonly sorting = signal<SortingState>([
{
id: 'age',
desc: true, //sort by age in descending order by default
}
])
readonly pagination = signal<PaginationState>({
pageIndex: 0,
pageSize: 15
})
//Use our controlled state values to fetch data
readonly data$ = combineLatest({
filters: toObservable(this.columnFilters),
sorting: toObservable(this.sorting),
pagination: toObservable(this.pagination)
}).pipe(
switchMap(({filters, sorting, pagination}) => fetchData(filters, sorting, pagination))
)
readonly data = toSignal(this.data$);
readonly table = createAngularTable(() => ({
columns: this.columns,
data: this.data(),
//...
state: {
columnFilters: this.columnFilters(), //pass controlled state back to the table (overrides internal state)
sorting: this.sorting(),
pagination: this.pagination(),
},
onColumnFiltersChange: updater => { //hoist columnFilters state into our own state management
updater instanceof Function
? this.columnFilters.update(updater)
: this.columnFilters.set(updater)
},
onSortingChange: updater => {
updater instanceof Function
? this.sorting.update(updater)
: this.sorting.set(updater)
},
onPaginationChange: updater => {
updater instanceof Function
? this.pagination.update(updater)
: this.pagination.set(updater)
},
}))
}
//...
import {signal} from '@angular/core';
import {SortingState, ColumnFiltersState, PaginationState} from '@tanstack/angular-table'
import {toObservable} from "@angular/core/rxjs-interop";
import {combineLatest, switchMap} from 'rxjs';
class TableComponent {
readonly columnFilters = signal<ColumnFiltersState>([]) //no default filters
readonly sorting = signal<SortingState>([
{
id: 'age',
desc: true, //sort by age in descending order by default
}
])
readonly pagination = signal<PaginationState>({
pageIndex: 0,
pageSize: 15
})
//Use our controlled state values to fetch data
readonly data$ = combineLatest({
filters: toObservable(this.columnFilters),
sorting: toObservable(this.sorting),
pagination: toObservable(this.pagination)
}).pipe(
switchMap(({filters, sorting, pagination}) => fetchData(filters, sorting, pagination))
)
readonly data = toSignal(this.data$);
readonly table = createAngularTable(() => ({
columns: this.columns,
data: this.data(),
//...
state: {
columnFilters: this.columnFilters(), //pass controlled state back to the table (overrides internal state)
sorting: this.sorting(),
pagination: this.pagination(),
},
onColumnFiltersChange: updater => { //hoist columnFilters state into our own state management
updater instanceof Function
? this.columnFilters.update(updater)
: this.columnFilters.set(updater)
},
onSortingChange: updater => {
updater instanceof Function
? this.sorting.update(updater)
: this.sorting.set(updater)
},
onPaginationChange: updater => {
updater instanceof Function
? this.pagination.update(updater)
: this.pagination.set(updater)
},
}))
}
//...
或者,您可以使用 onStateChange
表格选项控制整个表格状态。它会将整个表格状态提升到您自己的状态管理系统中。请谨慎使用此方法,因为您可能会发现将某些频繁更改的状态值(例如 columnSizingInfo
状态)提升到组件树中可能会导致糟糕的性能问题。
可能需要一些额外的技巧才能使其工作。如果您使用 onStateChange
表格选项,则 state
的初始值必须填充您要使用的所有功能的所有相关状态值。您可以手动键入所有初始状态值,或者以特殊方式使用构造函数,如下所示。
class TableComponent {
// create an empty table state, we'll override it later
readonly state = signal({} as TableState);
// create a table instance with default state values
readonly table = createAngularTable(() => ({
columns: this.columns,
data: this.data(),
// our fully controlled state overrides the internal state
state: this.state(),
onStateChange: updater => {
// any state changes will be pushed up to our own state management
this.state.set(
updater instanceof Function ? updater(this.state()) : updater
)
}
}))
constructor() {
// set the initial table state
this.state.set({
// populate the initial state with all of the default state values
// from the table instance
...this.table.initialState,
pagination: {
pageIndex: 0,
pageSize: 15, // optionally customize the initial pagination state.
},
})
}
}
class TableComponent {
// create an empty table state, we'll override it later
readonly state = signal({} as TableState);
// create a table instance with default state values
readonly table = createAngularTable(() => ({
columns: this.columns,
data: this.data(),
// our fully controlled state overrides the internal state
state: this.state(),
onStateChange: updater => {
// any state changes will be pushed up to our own state management
this.state.set(
updater instanceof Function ? updater(this.state()) : updater
)
}
}))
constructor() {
// set the initial table state
this.state.set({
// populate the initial state with all of the default state values
// from the table instance
...this.table.initialState,
pagination: {
pageIndex: 0,
pageSize: 15, // optionally customize the initial pagination state.
},
})
}
}
到目前为止,我们已经看到 on[State]Change
和 onStateChange
表格选项可以“提升”表格状态更改到我们自己的状态管理中。但是,关于使用这些选项,您应该注意一些事项。
state
选项中具有其对应的状态值。指定 on[State]Change
回调会告诉表格实例这将是一个受控状态。如果您未指定相应的 state
值,则该状态将“冻结”为其初始值。
class TableComponent {
sorting = signal<SortingState>([])
table = createAngularTable(() => ({
columns: this.columns,
data: this.data(),
//...
state: {
sorting: this.sorting(), // required because we are using `onSortingChange`
},
onSortingChange: updater => { // makes the `state.sorting` controlled
updater instanceof Function
? this.sorting.update(updater)
: this.sorting.set(updater)
}
}))
}
class TableComponent {
sorting = signal<SortingState>([])
table = createAngularTable(() => ({
columns: this.columns,
data: this.data(),
//...
state: {
sorting: this.sorting(), // required because we are using `onSortingChange`
},
onSortingChange: updater => { // makes the `state.sorting` controlled
updater instanceof Function
? this.sorting.update(updater)
: this.sorting.set(updater)
}
}))
}
on[State]Change
和 onStateChange
回调的工作方式与 React 中的 setState
函数完全相同。更新器值可以是新的状态值,也可以是接受先前状态值并返回新状态值的回调函数。
这有什么含义?这意味着如果您想在任何 on[State]Change
回调中添加一些额外的逻辑,您可以这样做,但是您需要检查新的传入更新器值是函数还是值。
这就是为什么您会在上面的示例中看到 updater instanceof Function ? this.state.update(updater) : this.state.set(updater)
模式的原因。此模式检查更新器是否为函数,如果是,则使用先前的状态值调用该函数以获取新的状态值,否则信号将需要使用更新器调用 signal.update
而不是 signal.set
。
TanStack Table 中的所有复杂状态都有自己的 TypeScript 类型,您可以导入和使用。这对于确保您为正在控制的状态值使用正确的数据结构和属性非常有用。
import {createAngularTable, type SortingState} from '@tanstack/angular-table'
class TableComponent {
readonly sorting = signal<SortingState>([
{
id: 'age', // you should get autocomplete for the `id` and `desc` properties
desc: true,
}
])
}
import {createAngularTable, type SortingState} from '@tanstack/angular-table'
class TableComponent {
readonly sorting = signal<SortingState>([
{
id: 'age', // you should get autocomplete for the `id` and `desc` properties
desc: true,
}
])
}
您每周的 JavaScript 新闻。每周一免费发送给超过 10 万名开发者。