- 页码向上取整 Math.ceil([].length / 每页现实的数量)
2. 动态修改 data,利用响应式原理,数组改变,组件自动重新渲染const [page, pageSize] = [1, 10];const startIndex = (page - 1) * pageSize; // 1-1 = 0 * 10 = 0; 2-1 = 1 * 10 = 10const data = data.slice(startIndex, startIndex + pageSize);
PageTable
前端 Table分页
import React, { useState, useMemo, useEffect } from 'react';import { array, number } from 'prop-types';import TableList from './TableList';PageTable.propTypes = {dataSource: array.isRequired,current: number,pageSize: number,};PageTable.defaultProps = {current: 1,pageSize: 10,};function PageTable({ dataSource, current: _c, pageSize: _p, ...rest }) {const [query, setQuery] = useState({ current: _c, pageSize: _p });const [state, setState] = useState([]);const total = useMemo(() => {return Array.isArray(dataSource) ? dataSource.length : 0;},[dataSource]);useEffect(update, [dataSource, query]);function update() {const { current, pageSize } = query;const startIndex = (current - 1) * pageSize;const _state = dataSource.slice(startIndex, startIndex + pageSize);setState(_state);}function pageChange({ current, pageSize }) {setQuery({ current, pageSize });}return (<TableList{...rest}{...query}total={total}dataSource={state}onChange={pageChange}/>);}export default PageTable;
前端分页原理
计算出数组的 startIndex, endIndex,
然后 slice截取当前区间的数据
const startIndex = (page - 1) * pageSize;const endIndex = startIndex + pageSize;// 1-1 = 0 * 10 = 0, 0 + 10;// 2-1 = 1 * 10 = 10, 10 + 10;// 3-1 = 2 * 10 = 20, 20 + 10;// 4-1 = 3 * 10 = 30, 30 + 10;// 5-1 = 4 * 10 = 40, 40 + 10;// 6-1 = 5 * 10 = 50, 50 + 10;// 7-1 = 7 * 10 = 60, 60 + 10;
pagination
jquery 分页插件
https://pagination.js.org/
