ant-design/components/table/hooks/usePagination.ts
Wuxh 951e0e2c79
fix(list): fix error reported due to incorrect paginator parameters (#39681)
* fix(list): fix pagination parameter error

* test: add case

* test: update snapshot

* chore: update case

* feat(util): add mergeProps

ref: 3c87f1c5b1/src/utils/with-default-props.tsx (L5)

* chore: replace method

* chore: rename
2022-12-24 15:05:33 +08:00

89 lines
2.6 KiB
TypeScript

import { useState } from 'react';
import type { PaginationProps } from '../../pagination';
import type { TablePaginationConfig } from '../interface';
import extendsObject from '../../_util/extendsObject';
export const DEFAULT_PAGE_SIZE = 10;
export function getPaginationParam(
pagination: TablePaginationConfig | boolean | undefined,
mergedPagination: TablePaginationConfig,
) {
const param: any = {
current: mergedPagination.current,
pageSize: mergedPagination.pageSize,
};
const paginationObj = pagination && typeof pagination === 'object' ? pagination : {};
Object.keys(paginationObj).forEach((pageProp) => {
const value = (mergedPagination as any)[pageProp];
if (typeof value !== 'function') {
param[pageProp] = value;
}
});
return param;
}
export default function usePagination(
total: number,
pagination: TablePaginationConfig | false | undefined,
onChange: (current: number, pageSize: number) => void,
): [TablePaginationConfig, () => void] {
const { total: paginationTotal = 0, ...paginationObj } =
pagination && typeof pagination === 'object' ? pagination : {};
const [innerPagination, setInnerPagination] = useState<{
current?: number;
pageSize?: number;
}>(() => ({
current: 'defaultCurrent' in paginationObj ? paginationObj.defaultCurrent : 1,
pageSize:
'defaultPageSize' in paginationObj ? paginationObj.defaultPageSize : DEFAULT_PAGE_SIZE,
}));
// ============ Basic Pagination Config ============
const mergedPagination = extendsObject<Partial<TablePaginationConfig>>(
innerPagination,
paginationObj,
{
total: paginationTotal > 0 ? paginationTotal : total,
},
);
// Reset `current` if data length or pageSize changed
const maxPage = Math.ceil((paginationTotal || total) / mergedPagination.pageSize!);
if (mergedPagination.current! > maxPage) {
// Prevent a maximum page count of 0
mergedPagination.current = maxPage || 1;
}
const refreshPagination = (current?: number, pageSize?: number) => {
setInnerPagination({
current: current ?? 1,
pageSize: pageSize || mergedPagination.pageSize,
});
};
const onInternalChange: PaginationProps['onChange'] = (current, pageSize) => {
if (pagination) {
pagination.onChange?.(current, pageSize);
}
refreshPagination(current, pageSize);
onChange(current, pageSize || mergedPagination?.pageSize!);
};
if (pagination === false) {
return [{}, () => {}];
}
return [
{
...mergedPagination,
onChange: onInternalChange,
},
refreshPagination,
];
}