Sorry, your browser cannot access this site
This page requires browser support (enable) JavaScript
Learn more >

引入并使用

关于分页的所有数据和方法都是 usePaginationState 返回的

1
2
3
import usePaginationState from '@/hooks/usePaginationState';
const ExpressRule = (props: IExpressRuleProps) => {
const [page, size, total, pageChange, setTotal, calcPage] = usePaginationState();

当删除发生时

删除时调用 calcPage 传入本次删除的数量,注意需要请求列表接口配合

1
2
3
4
5
6
7
8
9
10
11
12
const ruleDelete = (id: number) => {
props.dispatch({
type: 'settings/ruleDelete',
payload: {
id,
},
callback: () => {
message.success('删除成功');
getExpressRuleList(calcPage(-1));
},
});
};

请求列表

需要在请求列表中预设参数,第一个参数是页数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const getExpressRuleList = (pageV?: number, sizeV?: number, centerNameV?: string) => {
props.dispatch({
type: 'settings/ruleSelect',
payload: {
pageNum: pageV || page,
pageSize: sizeV || size,
centerName: centerNameV || center,
},
callback: (res: any) => {
if (res) {
setList(res.contents);
setTotal(res.total);
}
},
});
}

实现代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import { useCallback, useState } from 'react';

export default function usePaginationState(pageValue = 1, sizeValue = 10, totalValue = 0) {
const [page, setPage] = useState(pageValue);
const [size, setSize] = useState(sizeValue);
const [total, setTotal] = useState(totalValue);
// 分页切换
const pageChange = (newPage: any, newSize: any): any => {
setPage(newPage);
setSize(newSize);
};
// 计算页, 用于处理删除数据的情况,newTotalChange = -1表示删除了一个元素
const calcPage = useCallback((newTotalChange: number) => {
const maxPage = Math.ceil((total + newTotalChange) / size);
return (maxPage === Math.ceil(total / size) || page <= maxPage) ? page : maxPage;
}, [page, size, total]);
const arr: [
number,
number,
number,
(newPage: any, newSize: any) => any,
React.Dispatch<React.SetStateAction<number>>,
(newTotalChange: number) => number,
] = [page, size, total, pageChange, setTotal, calcPage];
return arr;
}