Open Eric-art-coder opened 7 months ago
在react+antd项目中,一些后台管理系统的table需求
import { useState, useEffect } from 'react'
import { message } from 'antd'
import { v4 as uuidv4 } from 'uuid'
export const useTableConfig = (initParams, setInitParams, callback) {
const [isLoading, setIsLoading] = useState(false)
const [pagination, setPagination] = useState({
position: 'bottomRight',
pageSize: 15,
total: 0,
current: 1
})
const [dataSource, setDataSource] = useState<Array<any>>([])
const onSearch = async (searchParams, obj: any) => {
if (isLoading) return
setIsLoading(true)
try {
const { data, code, msg } = await callback(searchParams, obj.current, obj.pageSize)
if (code == 200) {
data.list.forEach((item) => {
item.key = item.id || uuidv4()
})
setPagination({
...obj,
total: data.total
})
setInitParams(searchParams)
setDataSource(data.list)
} else {
message.error(msg)
}
} catch (e) {
message.error(e.message)
} finally {
setIsLoading(false)
}
}
useEffect(() => {
onSearch(initParams, pagination)
}, [])
return {
isLoading,
pagination,
dataSource,
setIsLoading,
setPagination,
setDataSource,
onSearch
}
}
import { useTableConfig } from '@/hooks/useTable'
import { Table, message } from 'antd'
const {
isLoading,
pagination,
dataSource,
setIsLoading,
setPagination,
setDataSource,
onSearch
} = useTableConfig(tenantParams, setTenantParams, selectTenants)
<Table
columns={columns}
dataSource={dataSource}
loading={isLoading}
pagination={pagination}
onChange={pageSizeOnChange}
/>
// 其他的一些
背景
很多后台管理系统都需要筛选条件、搜索等功能
核心实现
使用示例