reactjs - usePagination custom-hooks with material-ui 在 Pagination 组件中使用 next 和 prev 函数作为道具
问题描述
我已经使用自定义钩子与 material-ui 进行分页。该组件在第一页上工作正常,但调用 next()
,prev()
并且jump()
不起作用。我试图next={next}
作为道具传递。我从这里阅读了 api 文档,但找不到调用上述函数的正确方法。这是 usePagination.jsx 自定义钩子的代码
import React, { useState } from "react";
function usePagination(data, itemsPerPage) {
const [currentPage, setCurrentPage] = useState(1);
const maxPage = Math.ceil(data.length / itemsPerPage);
function currentData() {
const begin = (currentPage - 1) * itemsPerPage;
const end = begin + itemsPerPage;
return data.slice(begin, end);
}
function next() {
setCurrentPage((currentPage) => Math.min(currentPage + 1, maxPage));
}
function prev() {
setCurrentPage((currentPage) => Math.max(currentPage - 1, 1));
}
function jump(page) {
const pageNumber = Math.max(1, page);
setCurrentPage((currentPage) => Math.min(pageNumber, maxPage));
}
return {
next, prev, jump, currentData,
currentPage, maxPage
};
}
export default usePagination;
这是我的 Courses.jsx,我想在其中显示带有分页的课程列表。
import React, { useState, useEffect } from "react";
import {connect} from 'react-redux';
import CourseList from "./CourseList" ;
import usePagination from "./usePagination";
import * as actions from "../_actions/courseActions";
import CourseForm from "./CourseForm";
import { Grid, Paper, TableContainer, Table, TableHead, TableRow, TableCell, TableBody, withStyles, ButtonGroup, Button } from "@material-ui/core";
import { useToasts } from "react-toast-notifications";
import { makeStyles } from '@material-ui/core/styles';
import Pagination from '@material-ui/lab/Pagination';
const useStyles = makeStyles((theme) => ({
root: {
'& > *': {
marginTop: theme.spacing(2),
},
},
}));
const Courses =(props)=> {
const classes = useStyles();
useEffect(() => {
props.fetchAllCourses()
}, [])
// pagination code here
const { next, prev,
jump, currentData,
currentPage, maxPage }
=usePagination(props.courseList,4);
console.log("total pages:"+ maxPage)
return(
<div >
<CourseList
courseList={currentData()}
deleteCourse={props.deleteCourse}
createCourse={props.createCourse}
updateCourse={props.updateCourse}
/>
<div className={classes.root}>
<Pagination count={maxPage}
color="primary" />
</div>
</div>
);
}
const mapStateToProps= (state) =>({
courseList:state.course.list
})
const mapActionToProps={
fetchAllCourses:actions.fetchAll,
deleteCourse:actions.Delete,
createCourse:actions.create,
updateCourse:actions.update,
fetchCourse:actions.fetchById
}
export default connect(mapStateToProps,mapActionToProps)(Courses);
提前感谢您的帮助。
解决方案
推荐阅读
- python - Python 包设置:setup.py 自定义处理包装的 fortran
- java - HttpClient : 读入 file:// 目标中的文本文件
- sql - 在 SQL Server 中使用表变量参数优化存储过程的最佳方法是什么?
- python - 如何构建包含系统参数的 json?
- regex - 重复模式的正则表达式
- excel - 使用两个下拉菜单从另一张表中收集特定信息
- javascript - 比较javascript中的时间戳
- android - 使用 API 将 OBB 扩展文件上传到 Google Play 草案工件
- python - Seaborn 和 Pandas:使用 python 中的多索引数据制作多个 x 类别条形图
- sql - sql语句在复杂的where语句中更新多行中的多个值