- 设置分页表格相关参数
const [page, setPage] = useState(1);
const [count, setCount] = useState(0);
const [loading, setLoading] = useState(false);
const [dataSource, setDataSource] = useState<
{
id: number; message: string }[]
>([]);
- 使用antd的table组件,并传入相关参数
<Table
rowKey="id"
dataSource={
dataSource}
pagination={
{
current: page,
total: count,
pageSize: 8,
onChange: onPageChange
}}
loading={
loading}
columns={
[
{
title: 'id',
dataIndex: 'id',
key: 'id'
},
{
title: '信息',
dataIndex: 'message',
key: 'message',
render: (_, record: any) => {
return <>{
`${
record.id}-${
_}`}</>;
}
}
]}
/>
- 封装请求方法,设置loadin及相关数据(其中fetchList为fetch请求)
const serviceFn = useCallback(
(pagination: {
current?: number; pageSize?: number }) => {
setLoading(true);
return fetchList({
page: {
to: pagination.current || page,
size: pagination.pageSize || 8
}
})
.then(data => {
setCount(data.dataCount);
setDataSource(data.data);
})
.finally(() => {
setLoading(false);
});
},
[page]
);
- 使用定时器实现轮询
const timer = useRef<number>();
const getList = useCallback(
(params: {
current?: number; pageSize?: number }) => {
serviceFn(params);
clearInterval(timer.current);
timer.current = window.setInterval(() => {
serviceFn(params);
}, 5000);
},
[serviceFn]
);
- 初始化时发送请求,设置定时器
useEffect(() => {
getList({
});
return () => {
clearInterval(timer.current);
};
}, []);
- 当table切换当前页时会触发onChange事件,定义onPageChange事件
const onPageChange = useCallback(
(current: number) => {
getList({
current
});
setPage(current);
},
[getList]
);
- 完整代码
import React, {
useState, useEffect, useCallback, useRef } from 'react';
import {
Table } from 'antd';
const App = () => {
const timer = useRef<number>();
const [page, setPage] = useState(1);
const [count, setCount] = useState(0);
const [loading, setLoading] = useState(false);
const [dataSource, setDataSource] = useState<
{
id: number; message: string }[]
>([]);
const serviceFn = useCallback(
(pagination: {
current?: number; pageSize?: number }) => {
setLoading(true);
return fetchList({
page: {
to: pagination.current || page,
size: pagination.pageSize || 8
}
})
.then(data => {
setCount(data.dataCount);
setDataSource(data.data);
})
.finally(() => {
setLoading(false);
});
},
[page]
);
const getList = useCallback(
(params: {
current?: number; pageSize?: number }) => {
serviceFn(params);
clearInterval(timer.current);
timer.current = window.setInterval(() => {
serviceFn(params);
}, 5000);
},
[serviceFn]
);
useEffect(() => {
getList({
});
return () => {
clearInterval(timer.current);
};
}, []);
const onPageChange = useCallback(
(current: number) => {
getList({
current
});
setPage(current);
},
[getList]
);
return (
<Table
rowKey="id"
dataSource={
dataSource}
pagination={
{
current: page,
total: count,
pageSize: 8,
onChange: onPageChange
}}
loading={
loading}
columns={
[
{
title: 'id',
dataIndex: 'id',
key: 'id'
},
{
title: '信息',
dataIndex: 'message',
key: 'message',
render: (_, record: any) => {
return <>{
`${
record.id}-${
_}`}</>;
}
}
]}
/>
);
};
export default App;
文章评论