分页统一管理功能 usePaginationState使用说明,包含减少数据时更新页数功能
引入并使用
关于分页的所有数据和方法都是 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); }; 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; }
|