react 如何分页
分页的实现方法
在React中实现分页功能通常需要结合前端状态管理和API请求。以下是几种常见的实现方式:
客户端分页
当数据量较小时,可以在前端直接进行分页处理:
const [currentPage, setCurrentPage] = useState(1);
const itemsPerPage = 10;
// 假设data是从API获取的完整数据集
const indexOfLastItem = currentPage * itemsPerPage;
const indexOfFirstItem = indexOfLastItem - itemsPerPage;
const currentItems = data.slice(indexOfFirstItem, indexOfLastItem);
const paginate = (pageNumber) => setCurrentPage(pageNumber);
服务器端分页
对于大数据集,建议使用服务器端分页:
const [currentPage, setCurrentPage] = useState(1);
const [totalPages, setTotalPages] = useState(0);
const [items, setItems] = useState([]);
useEffect(() => {
const fetchData = async () => {
const response = await fetch(`/api/items?page=${currentPage}&limit=10`);
const { data, total } = await response.json();
setItems(data);
setTotalPages(Math.ceil(total / 10));
};
fetchData();
}, [currentPage]);
分页组件实现
创建一个可复用的分页组件:
function Pagination({ currentPage, totalPages, onPageChange }) {
const pages = Array.from({ length: totalPages }, (_, i) => i + 1);
return (
<div className="pagination">
<button
onClick={() => onPageChange(currentPage - 1)}
disabled={currentPage === 1}
>
Previous
</button>
{pages.map(page => (
<button
key={page}
onClick={() => onPageChange(page)}
className={currentPage === page ? 'active' : ''}
>
{page}
</button>
))}
<button
onClick={() => onPageChange(currentPage + 1)}
disabled={currentPage === totalPages}
>
Next
</button>
</div>
);
}
使用现有库
可以考虑使用现成的分页库如react-paginate:
import ReactPaginate from 'react-paginate';
function MyComponent() {
const handlePageClick = (data) => {
const selectedPage = data.selected + 1;
// 更新当前页码或获取新数据
};
return (
<ReactPaginate
previousLabel={'previous'}
nextLabel={'next'}
breakLabel={'...'}
pageCount={20}
marginPagesDisplayed={2}
pageRangeDisplayed={5}
onPageChange={handlePageClick}
containerClassName={'pagination'}
activeClassName={'active'}
/>
);
}
分页样式优化
为分页组件添加基本CSS样式:
.pagination {
display: flex;
justify-content: center;
margin-top: 20px;
}
.pagination button {
margin: 0 5px;
padding: 5px 10px;
border: 1px solid #ddd;
background: white;
cursor: pointer;
}
.pagination button.active {
background: #007bff;
color: white;
border-color: #007bff;
}
.pagination button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
性能考虑
对于大数据集,实现无限滚动可能是更好的选择:
const [items, setItems] = useState([]);
const [page, setPage] = useState(1);
const [hasMore, setHasMore] = useState(true);
const fetchMoreData = () => {
fetch(`/api/items?page=${page}`)
.then(res => res.json())
.then(data => {
setItems([...items, ...data]);
setPage(page + 1);
if (data.length === 0) setHasMore(false);
});
};
// 在滚动监听中使用
window.addEventListener('scroll', () => {
if (window.innerHeight + document.documentElement.scrollTop ===
document.documentElement.offsetHeight && hasMore) {
fetchMoreData();
}
});






