1.基本使用
使用 useAntdTable 的form 实现与 table 的联动
import React, { useEffect } from 'react'
import { Form, Table, message } from 'antd'
import { useAntdTable } from 'ahooks'
function AppPush() {
const getAppPushList = async (params, form) => {
const page = {
pageSize: params.pageSize,
pageNum: params.current,
}
try {
const data = await http.postJson('/',{
...page,
...form,
})
return Promise.resolve({
list: data.data,
total: data.page.rowCount,
})
} catch (err) {
message.error(`错误:${err.code}`)
return Promise.reject(err)
}
}
const [form] = Form.useFoorm()
const { tableProps, search, params, run } = useAntdTable(getAppPushList, {
defaultPageSize: 10,
form,
})
tableProps.pagination.size = 'small'
tableProps.pagination.showTotal = total => `共${total} 条记录`
const { submit, reset } = search
const { loading } = tableProps
const columns = [
{
title: '序号',
width: 60,
align: 'center',
render: (_, _, index) => {
return (params[0]?.current-1)*params[0]?.pageSize+(index+1)
}
},
{
title: '所属分组',
dataIndex: 'groupName',
width: 300,
render: (text, record, _) => {
return text || '--'
},
onCell: () => ({
style: {
whiteSpace: 'nowrap'
},
}),
onHeaderCell: () => ({
style: {
whiteSpace: 'nowrap'
},
}),
}
]
return (
<div>
<Table columns={columns} size='small' bordered={true} {...tableProps} rowKey='sn' />
</div>
)
}
export default AppPush
2.遇到的问题
(1)接口调用了两次
背景:每次监听到分组作用域变化后,刷新页面更新数据,初始化时发现该接口调用了两次。
原因:初始化时, useAntdTable 会调用一次接口,同时分组作用域由 undefined 变为有值,也会调用一次接口。
解决:使用 refreshDeps 监听分组作用域变化,重新发起请求。
const { tableProps, search, params } = useAntdTable(getAppPushList, {
defaultPageSize: 10,
form,
})
useEffect(() => {
getAppPushList()
setFieldsValue({ modelIds: [] })
}, [defaultGroup.value])
改进代码:
const { tableProps, search, params } = useAntdTable(getAppPushList, {
defaultPageSize: 10,
form,
refreshDeps:[defaultGroup.value]
})
(2)刷新并停留在当前页面
背景 & 原因:refreshDeps 变化,会重置 current 到第一页,并重新发起请求,需要刷新并停留在当前页面。
解决:由于 useAntdTable 是基于useRequest 封装的,查询其 API,发现 run 会向外暴露手动触发 service 执行,并将当前页数等参数传递给 service
const run: (params_0: {
[key: string]: any;
current: number;
pageSize: number;
sorter?: any;
filter?: any;
}, ...params_1: any[]) => void
改进代码:
const { tableProps, search, params, run } = useAntdTable(getAppPushList, {
defaultPageSize: 10,
form,
})
...
run({current:tableProps.pagination.current, pageSize:10})