前端分页开发:如何从API获取并展示全部第一页博客文章
解决方案:展示所有博客文章并实现前端分页
问题分析
原代码存在两个核心问题:
- 数据处理错误:
postData.push(post?.datas?.data)将接口返回的文章数组包装成二维数组,导致后续无法正确遍历 - 渲染逻辑局限:仅通过
post?.datas?.data[0]渲染单篇文章,未遍历所有数据
修改步骤及完整代码
import { useState } from 'react'; // 假设useFetch是已实现的自定义hook function Posts() { const { data: post, loading, error } = useFetch("https://accounts.com/api/blogs"); // 分页状态管理 const [currentPage, setCurrentPage] = useState(1); const [postsPerPage] = useState(6); // 可根据需求调整每页展示数量 if (loading) return <h1>Loading...</h1>; if (error) console.error("博客数据获取失败:", error); // 修正数据处理:直接获取文章数组,为空则返回空数组 const postData = post?.datas?.data || []; // 计算当前页需展示的文章 const indexOfLastPost = currentPage * postsPerPage; const indexOfFirstPost = indexOfLastPost - postsPerPage; const currentPosts = postData.slice(indexOfFirstPost, indexOfLastPost); // 分页按钮切换逻辑 const paginate = (pageNumber) => setCurrentPage(pageNumber); const goToPrevPage = () => setCurrentPage(prev => Math.max(prev - 1, 1)); const goToNextPage = () => setCurrentPage(prev => Math.min(prev + 1, Math.ceil(postData.length / postsPerPage))); return ( <> {/* 博客列表渲染 */} <div className="blogPost"> <div className="row"> {currentPosts.map((item, index) => ( <div key={index} className="col-4 mb-5"> <div className="post container px-5 pb-5"> <div className="card-img-top"> <img src={`https://accounts.com/${item.attachment?.media_url || ''}`} alt={item.title || "博客封面"} onError={(e) => e.target.src = "默认封面图片地址"} // 可选:添加图片加载失败兜底 /> </div> <div className="card"> <div className="postBody"> <div className="postBodyinner pt-4 px-4 d-flex justify-content-between"> <h5 className="postTitle">{item.title}</h5> <h5 className="views">{item.views || 0} 次浏览</h5> {/* 假设接口返回views字段 */} </div> <p className="card-desc px-4"> {item.content.substring(0, 100)}... {/* 可选:截取摘要,避免内容过长 */} {/* <Link to={`/blog/${item.id}`}>查看全文</Link> */} {/* 可选:添加详情页跳转 */} </p> <div className="postBottom px-4 d-flex justify-content-between pb-3"> <p>{new Date(item.created_at).toLocaleDateString()}</p> {/* 假设接口返回创建时间 */} </div> </div> </div> </div> </div> ))} </div> </div> {/* 分页控件 */} {postData.length > postsPerPage && ( <div className="d-flex justify-content-center mt-5"> <button onClick={goToPrevPage} disabled={currentPage === 1} className="btn btn-outline-secondary me-2" > 上一页 </button> {Array.from({ length: Math.ceil(postData.length / postsPerPage) }, (_, i) => ( <button key={i+1} onClick={() => paginate(i+1)} className={`btn mx-1 ${currentPage === i+1 ? 'btn-primary' : 'btn-outline-primary'}`} > {i+1} </button> ))} <button onClick={goToNextPage} disabled={currentPage === Math.ceil(postData.length / postsPerPage)} className="btn btn-outline-secondary ms-2" > 下一页 </button> </div> )} </> ); } export default Posts;
关键改动说明
- 数据处理修正:将错误的二维数组生成逻辑改为直接获取接口返回的文章数组,避免遍历异常
- 分页状态添加:使用
useState管理当前页码和每页展示数量,通过数组切片slice筛选当前页内容 - 批量渲染文章:用
map遍历当前页文章数组,为每个文章生成独立卡片,添加唯一key确保React渲染稳定性 - 分页控件实现:生成对应数量的页码按钮,添加上下页切换逻辑,通过
disabled属性控制按钮可用性 - 细节优化:修复图片路径错误、添加图片加载失败兜底、展示文章摘要和创建时间等实用信息
内容的提问来源于stack exchange,提问作者Jasraj Singh
相关产品推荐
相关产品推荐

