文章目录
本文提供两种分页思路
- 纯 js 分页
- 使用lodash-es实现分页
一、纯js分页
(1)html
<div className={styles['fre-div']}>
<Row>
{list.map(
(item): JSX.Element => {
return (
<Col span={4} key={item.id} className={styles['fre-col']}>
<div className={styles['fre-col__div']}>
<p className={styles['fre-col__text']}>
<span>{item.xxx}次</span>
</p>
</div>
</Col>
);
},
)}
</Row>
</div>
<Pagination
onChange={handlePaginationChange}
defaultCurrent={pageIndex}
total={sumList.length}
pageSize={pageSize}
className={styles['page-div']}
/>
</div>
(2)js代码
state变量声明不再做过多说明
1. list请求函数
const requestList = useCallback(async (params: CompareFreAnalyParams) => {
setLoading(true);
//每次请求时需要将数组内原有数据清空
setList([]);
try {
const { result } = await fetchCompareFreAnalyList(params);
setSumList(result);
//arrSplit 分页函数
setList(arrSplit(result, 1, pageSize));
} catch (e) {
message.warn(e.message || '获取数据失败');
}
setLoading(false);
}, []);
2. 分页组件函数
const handlePaginationChange = useCallback(
pagination => { //获得pageIndex
const list = arrSplit(sumList, pagination, pageSize);
setList(list);
},
[list],
);
3. 分页函数
export function arrSplit(arr: any[], index: number, size: number): any[] {
const offset = (index - 1) * size;
return offset + size >= arr.length ? arr.slice(offset, arr.length) : arr.slice(offset, offset + size);
}
二、lodash实现分页
(1)html代码
<div className={styles['fre-div']}>
<Row>
{current.map(
(item): JSX.Element => {
return (
<Col span={4} key={item.id} className={styles['fre-col']}>
<div className={styles['fre-col__div']}>
<img className={styles['fre-col__img']} src={item.imageUrl} alt="" />
<p className={styles['fre-col__text']}>
<span>{item.frequency}次</span>
<a onClick={handleDetail(item.account, item.number, item.name, item.bizCode)}>详情</a>
</p>
</div>
</Col>
);
},
)}
</Row>
</div>
<Pagination
onChange={handlePaginationChange}
defaultCurrent={pageIndex}
total={list.length}
pageSize={pageSize}
className={styles['page-div']}
/>
</div>
(2)js代码
1. 请求函数
const requestList = useCallback(async (params: CompareFreAnalyParams) => {
setLoading(true);
setList([]);
try {
const { result } = await fetchCompareFreAnalyList(params);
setList(result);
} catch (e) {
message.warn(e.message || '获取数据失败');
}
setLoading(false);
}, []);
2. 分页组件函数
const handlePaginationChange = useCallback(
pagination => {
const search = queryString.parse(location.search);
history.push({
pathname: location.pathname,
search: queryString.stringify({
...search,
pageIndex: pagination,
}),
});
},
[location.search, location.pathname, history],
);
3. 通过useMemo监听分页
import { chunk } from 'lodash-es';
const current = useMemo(() => {
return chunk(list, pageSize)[pageIndex - 1] || [];
}, [list, pageIndex]);