如何实现分页数据的上一页/下一页更新与视图渲染
解决分页按钮的URL拼接问题
嘿,我看了你的代码,发现分页功能的核心问题出在URL拼接错误上,顺便给你优化了一些细节提升稳定性,一起来看看:
问题根源
API返回的next_page/previous_page已经是完整的接口路径(比如/api/articles/ios_index?page=2),但你现在把它拼在了基础URLhttps:sample.sale/api/articles/ios_index后面,导致最终请求地址变成了重复的https:sample.sale/api/articles/ios_index/api/articles/ios_index?page=2,这肯定会请求失败。
修正后的完整代码
import React from 'react'; import axios from 'axios'; // 抽离基础域名,方便后续维护 const BASE_DOMAIN = "https:sample.sale"; export default class ArticleApi extends React.Component { constructor() { super(); this.state = { blogs: [], // 初始设为空数组,避免map方法报错 blogPages: {} // 初始设为空对象,防止读取pagination属性时抛出异常 } } // 重构fetchData,支持传入自定义路径,复用逻辑 fetchData = (path = "/api/articles/ios_index") => { axios.get(`${BASE_DOMAIN}${path}`) .then(res => { this.setState({ blogs: res.data.data, blogPages: res.data.metadata }) }) .catch(error => { console.error('请求出错啦: \n', error); }); } componentDidMount() { this.fetchData() } previousPage = () => { // 先判断是否存在上一页,避免无效请求 const prevPath = this.state.blogPages?.pagination?.previous_page; if (prevPath) { this.fetchData(prevPath); } } nextPage = () => { // 同样判断是否存在下一页 const nextPath = this.state.blogPages?.pagination?.next_page; if (nextPath) { this.fetchData(nextPath); } } render() { let feed = "Loading..."; // 确保blogs是数组且有内容时再渲染列表 if (Array.isArray(this.state.blogs) && this.state.blogs.length > 0) { feed = this.state.blogs.map((ele, idx) => { return ( <div key={idx} > <div className="articleContent"> <p><strong>{ele.franchise}</strong></p> <h1 className="title"> {ele.title}</h1> </div> </div> ) }) } // 判断是否有上/下一页,控制按钮状态 const hasPrevious = !!this.state.blogPages?.pagination?.previous_page; const hasNext = !!this.state.blogPages?.pagination?.next_page; return ( <div> <h3>FEED</h3> {feed} {/* 无对应分页时禁用按钮,提升用户体验 */} <button onClick={this.previousPage} disabled={!hasPrevious}> Previous Page </button> <button onClick={this.nextPage} disabled={!hasNext}> Next Page </button> </div> ) } }
关键优化点
- 修复URL拼接:直接用
基础域名 + API返回的分页路径,避免重复拼接接口前缀 - 复用请求逻辑:重构
fetchData函数,让上/下一页请求都复用同一个方法,减少冗余代码 - 状态初始化优化:给
blogs和blogPages设置更合理的初始值,避免组件渲染初期读取属性报错 - 分页按钮状态控制:通过判断是否存在对应分页路径,禁用/启用按钮,防止用户无效点击
- 语法错误修复:补上了
h3标签的闭合引号和标签
额外建议
- 可以添加loading状态,防止用户重复点击分页按钮
- 如果API在无更多数据时返回
null作为分页路径,记得保持当前的判断逻辑,避免发送无效请求
内容的提问来源于stack exchange,提问作者bruce
相关产品推荐
相关产品推荐

