You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React分页组件标记当前激活页面功能失效该如何解决?

实现方案

1. 初始化当前页码状态

在类组件的constructor中优先从localStorage读取保存的页码,读取失败则默认值为1,注意要将localStorage取出的字符串转为数字,避免后续判断类型不匹配:

constructor(props) {
  super(props);
  this.state = {
    currentPage: Number(localStorage.getItem('currentPage')) || 1
  }
}

2. 实现页码切换逻辑

点击页码时同时更新state和localStorage的存储值:

handleClick = (e) => {
  const targetPage = Number(e.target.id);
  this.setState({ currentPage: targetPage });
  localStorage.setItem('currentPage', targetPage);
  // 如需触发分页数据更新,可在此处添加对应逻辑
}

3. 渲染时添加高亮类

遍历页码数组时,直接判断当前循环的页码值是否等于state中存储的currentPage,相等则添加mark-page高亮类:

const pageNumbers = [];
for (let i = 1; i <= Math.ceil(allFacts.length / factsPerPage); i++) {
  pageNumbers.push(i);
}

// 可选补充:如果总页数变化时当前页码超出范围,自动重置为最后一页
const totalPage = pageNumbers.length;
if (this.state.currentPage > totalPage && totalPage > 0) {
  const resetPage = totalPage;
  this.setState({ currentPage: resetPage });
  localStorage.setItem('currentPage', resetPage);
}

const renderPageNumbers = pageNumbers.map((number) => {
  return (
    <button 
      key={number} 
      id={number} 
      onClick={this.handleClick}
      className={number === this.state.currentPage ? 'mark-page' : ''}
    >
      {number}
    </button>
  );
});

return <div id="paging">{renderPageNumbers}</div>;

常见问题说明

之前判断不生效大概率是类型不匹配导致:localStorage存储的值都是字符串类型,如果没有转成数字就和页码的数字类型做===全等判断,会始终返回false,导致高亮类无法正常添加。

内容的提问来源于stack exchange,提问作者user14964079

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 17:18:04