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

React Router参数变更时如何用useSWR Hook重新获取数据

问题原因与解决方案

你遇到的核心问题是useSWR的缓存key未随路由参数变化而更新,导致路由切换时SWR复用了旧缓存,没有重新发起请求;同时fetcher里的id是闭包捕获的初始值,无法响应参数更新。

解决方案步骤:

  • 将路由参数加入SWR的缓存key:SWR通过缓存key判断是否需要重新请求,把id整合进key,当id变化时,key也会变化,触发新的请求。
  • 修正fetcher逻辑:让fetcher能正确使用最新的路由参数,保证请求携带当前的post id。

修改后的Post.tsx代码:

// Post.tsx
export default function Post(){
  const {id} = useParams()
  const postId = parseInt(id)

  // 方式1:把postId拼接到请求URL中(适合RESTful接口)
  const {data} = useSWR(`http://localhost:80/post/${postId}`, (url) => 
    axios.get(url).then(res => res.data)
  )

  // 方式2:用数组作为缓存key(适合通过query参数传id的场景)
  // const {data} = useSWR(['http://localhost:80/post', postId], ([url, id]) => 
  //   axios.get(url, { params: { id } }).then(res => res.data)
  // )

  return <div>
           {/*display post content */}
         </div>
}

关键说明:

  • 当使用数组作为缓存key时,数组内任意元素变化,SWR都会判定为新请求,自动重新获取数据。
  • 完全不需要用useNavigate刷新页面,SWR本身就支持基于依赖变化的自动请求,这也是它比useEffect做数据请求更灵活的优势之一。

内容的提问来源于stack exchange,提问作者Trung Kiến

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 14:40:29