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

使用react-paginate刷新页面时useEffect失效,数据无法显示

问题分析与解决方案

问题根源

你的问题出在PaginatedItems组件的useEffect依赖配置上:

  • 该组件的useEffect仅监听了itemOffset和itemsPerPage,但未监听传入的items(即从Redux获取的posts)。
  • 页面刷新时,初始items为空数组,currentItems被设为null,此时Posts组件接收null无法渲染内容;当Redux异步获取到数据后,items更新,但因不在依赖数组中,useEffect不会重新执行,currentItems仍为null。
  • 切换菜单再返回时,PaginatedItems组件重新挂载,此时items已有数据,useEffect执行并正确计算currentItems,因此数据能正常显示。

修复步骤

1. 修正PaginatedItems的useEffect依赖

在pagination.js中,将items添加到useEffect的依赖数组,确保items更新时重新计算分页数据:

useEffect(() => {
  const endOffset = itemOffset + itemsPerPage;  
  setCurrentItems(items.slice(itemOffset, endOffset));
  setPageCount(Math.ceil(items.length / itemsPerPage));
}, [itemOffset, itemsPerPage, items]); // 新增items依赖

2. 优化初始状态(可选但推荐)

将currentItems的初始值从null改为空数组,避免Posts组件接收null:

const [currentItems, setCurrentItems] = useState([]);

3. 添加加载状态处理(可选)

在App.js中根据Redux状态添加加载提示,避免页面空白:

// 假设你的Redux state包含loading字段,例如state.posts.loading
const { posts, loading } = useSelector(state => state.posts);

// 在路由元素中添加加载判断
<Route path='/' exact element={
  loading ? <div>加载中...</div> : <PaginatedItems setCurrentId={setCurrentId} items={posts} />
} />

验证修复

修改后刷新页面,Redux获取到数据时,PaginatedItems会监听items的变化,自动重新计算分页数据并渲染内容,无需切换菜单即可正常显示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 16:16:02