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

React Query分页失效求助:点击下一页数据不更新

React Query分页数据不更新问题解决指南

核心问题排查与修复步骤

1. 确认查询键(Query Key)包含分页参数

React Query 通过查询键识别不同的缓存条目,如果查询键未包含 page,所有分页请求会复用同一缓存,导致数据不更新。

错误写法:

const { data } = useQuery(['colors'], () => 
  axios.get('/colors').then(res => res.data)
)

正确写法:
将当前页码加入查询键,确保不同分页请求生成独立缓存:

const { data } = useQuery(
  ['colors', currentPage], // 关键:查询键包含currentPage
  () => axios.get('/colors', { params: { _page: currentPage, _limit: 2 } }).then(res => res.data)
)

2. 修正JSON Server分页参数名称

JSON Server 要求分页使用 _page(页码)和 _limit(每页条数)作为查询参数,而非自定义的 page。如果参数名错误,JSON Server 会始终返回第一页数据。

验证方式:
直接在浏览器访问 http://localhost:3000/colors?_page=2&_limit=2,确认是否返回第二页数据。若返回第一页,说明参数名错误。

3. 确认页码状态正确更新

检查页码状态的维护逻辑,确保点击分页按钮时,currentPage 正确更新并触发组件重新渲染:

const [currentPage, setCurrentPage] = useState(1)

const handleNextPage = () => {
  setCurrentPage(prev => prev + 1)
}

4. 正确使用 keepPreviousData 选项

该选项用于分页切换时保留上一页数据(避免空白),但需配合正确的查询键使用。完整配置示例:

const { data: colors, isLoading } = useQuery(
  ['colors', currentPage],
  () => 
    axios.get('http://localhost:3001/colors', {
      params: {
        _page: currentPage,
        _limit: 2
      }
    }).then(res => res.data),
  {
    keepPreviousData: true,
    staleTime: 0 // 确保每次查询都发起新请求(可选,默认值为0)
  }
)

完整可运行代码示例

import { useState } from 'react'
import { useQuery } from 'react-query'
import axios from 'axios'

function ColorList() {
  const [currentPage, setCurrentPage] = useState(1)
  const pageSize = 2

  const { data: colors, isLoading } = useQuery(
    ['colors', currentPage],
    () => 
      axios.get('http://localhost:3001/colors', {
        params: { _page: currentPage, _limit: pageSize }
      }).then(res => res.data),
    { keepPreviousData: true }
  )

  if (isLoading) return <div>Loading...</div>

  return (
    <div>
      <ul>
        {colors.map(color => (
          <li key={color.id}>{color.label}</li>
        ))}
      </ul>
      <button 
        onClick={() => setCurrentPage(prev => Math.max(prev - 1, 1))} 
        disabled={currentPage === 1}
      >
        上一页
      </button>
      <button onClick={() => setCurrentPage(prev => prev + 1)}>
        下一页
      </button>
      <p>当前页:{currentPage}</p>
    </div>
  )
}

export default ColorList

额外验证步骤

  1. 检查控制台网络请求:点击分页按钮时,确认请求URL中包含正确的 _page 参数(如 _page=2)。
  2. 确认JSON Server数据量:确保 db.json 中的 colors 数组至少有3条数据,才能看到分页效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 02:33:32