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

React项目使用react-paginate时currentPage不更新无法翻页如何解决

问题原因及修复方案

你现在的代码有两处错误导致分页不生效:

  1. useEffect依赖项不全
    你当前的useEffect只把dispatch作为依赖,currentPage变化时不会重新触发拉取新页数据的逻辑,需要把currentPage加到依赖数组里。
  2. action函数参数定义错误
    redux thunk的异步action函数,第一个是你主动传入的参数,后面的dispatch、getState是thunk中间件自动注入的参数,你现在把currentPage写在了dispatch后面,永远拿不到正确的页码值。

具体修改代码

1. 修复HomeScreen组件的useEffect

// 修改前
useEffect(() => {
  dispatch(listProducts(currentPage));
  console.log(currentPage);
}, [dispatch]);

// 修改后
useEffect(() => {
  dispatch(listProducts(currentPage));
  console.log(currentPage);
}, [dispatch, currentPage]); // 加入currentPage作为依赖

2. 修复listProducts action的参数定义

// 修改前
export const listProducts = () => async (dispatch, currentPage) => {
  // 原有逻辑
}

// 修改后
export const listProducts = (currentPage) => async (dispatch) => {
  dispatch({
    type: PRODUCT_LIST_REQUEST,
  });
  try {
    const { data } = await Axios.get(`http://localhost:3000/items?_page=${currentPage}&_limit=16`);
    dispatch({ type: PRODUCT_LIST_SUCCESS, payload: data });
  } catch (error) {
    dispatch({ type: PRODUCT_LIST_FAIL, payload: error.message });
  }
};

可选优化

你当前ReactPaginate组件的pageCount写死成了40,建议接口返回总数据条数后,前端计算总页数赋值给pageCount,避免后端数据总量变化后分页显示异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 10:06:00