2023-10-30 05:07PM
1. 创建分页文件
2. 在文件中增加下面的内容
// src/article/page.js
import React, { useState, useEffect } from 'react';
function Pagination({ totalItems, itemsPerPage, onPageChange }) {
const [currentPage, setCurrentPage] = useState(1);
useEffect(() => {
setCurrentPage(1);
}, [totalItems, itemsPerPage]);
const totalPages = Math.ceil(totalItems / itemsPerPage);
const handlePageChange = (page) => {
setCurrentPage(page);
onPageChange(page);
};
return (
<div>
{Array.from({ length: totalPages }, (_, index) => index + 1).map((page) => (
<button key={page} onClick={() => handlePageChange(page)}>
{page}
</button>
))}
</div>
);
}
export default Pagination;
2. 在列表文件中引入<Pagination />组件:
// src/article/index.js
import React, { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import axios from 'axios';
import Pagination from './page';
function BlogList() {
const [articles, setArticles] = useState([]);
const [currentPage, setCurrentPage] = useState(1);
const itemsPerPage = 50;
useEffect(() => {
axios.get('http://your-api-url/articles')
.then(response => {
setArticles(response.data.articles);
})
.catch(error => {
console.error("请求错误:", error);
});
}, []);
const handlePageChange = (page) => {
setCurrentPage(page);
};
const startIndex = (currentPage - 1) * itemsPerPage;
const endIndex = startIndex + itemsPerPage;
const currentData = articles.slice(startIndex, endIndex);
return (
<div>
<h2>美亿的博客</h2>
<Pagination totalItems={articles.length} itemsPerPage={itemsPerPage} onPageChange={handlePageChange} />
<div>
{currentData.map(article => (
<div key={article.id}>
<div>
<Link to={`/articles/${article.id}`}>
<p>
{article.created_at}
{article.title}
</p>
</Link>
</div>
</div>
))}
</div>
<Pagination totalItems={articles.length} itemsPerPage={itemsPerPage} onPageChange={handlePageChange} />
</div>
);
}
export default BlogList;
我这里在列表页面增加了两个分页:
一个在列表页面的标题下面:
一个在列表页面底部:
登录
请登录后再发表评论。
评论列表:
目前还没有人发表评论