我在 NextJS 应用程序中使用 Tanstack React 表。
我已经用 globalFilter 实现了一个搜索字段,工作得很好。
我想管理 URL 中的状态而不是状态,以便搜索结果和视图可以在应用程序的用户之间共享。
我已经设法做到了这一点,但我相当确定我做错了,因为我现在正在状态和 URL 中管理状态。应该只是网址。我很困惑这是否可能,因为您必须将状态绑定到表,但想知道是否有人知道解决方案。
这是我的桌子:
'use client'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from '@/components/ui/table'
import {
ColumnDef,
ColumnFiltersState,
flexRender,
getCoreRowModel,
getFilteredRowModel,
getPaginationRowModel,
useReactTable,
} from '@tanstack/react-table'
import { set } from 'date-fns'
import { useSearchParams, useRouter } from 'next/navigation'
import { useEffect, useState } from 'react'
interface DataTableProps<TData, TValue> {
columns: ColumnDef<TData>[] | null
data: TData[] | null
}
export const DataTable = <TData extends TValue, TValue>({
columns,
data,
}: DataTableProps<TData, TValue>) => {
const [columnFilters, setColumnFilters] = useState<ColumnFiltersState>([])
const [globalFilter, setGlobalFilter] = useState<string>('')
const searchParams = useSearchParams()
const router = useRouter()
const q = searchParams.get('q') || ''
const table = useReactTable({
data: data || [],
columns: columns || [],
getCoreRowModel: getCoreRowModel(),
getPaginationRowModel: getPaginationRowModel(),
onColumnFiltersChange: setColumnFilters,
getFilteredRowModel: getFilteredRowModel(),
state: {
columnFilters,
globalFilter,
},
onGlobalFilterChange: setGlobalFilter,
})
useEffect(() => {
setGlobalFilter(q)
}, [globalFilter, q])
//TODO i think global filter should be handled by the url only not also state
return (
<div>
<div className='flex items-center justify-end pb-4 '>
<Input
placeholder='Search...'
value={globalFilter}
onChange={(e) => {
setGlobalFilter(e.target.value)
router.push(`?q=${e.target.value}`, { scroll: false })
}}
className='max-w-sm w-[250px]'
/>
</div>
<div>
// table omitted for readability.
</div>
<div className='flex items-center justify-end space-x-2 py-4'>
// pagination omitted for readability
</div>
</div>
)
}
尝试将 globalFilter 绑定到表配置对象中的 url searchParams,如下所示:
state: { columnFilters, globalFilter: q, },
然后只需删除 [globalFilter, setGlobalFilter]
useState() 调用和任何相关代码(从表配置中删除 onGlobalFilterChange,删除 useEffect,从 onChange 处理程序中删除 setGlobalFilter,将输入值更改为 value={q})