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

React Router v6使用navigate函数进行路由跳转时如何传递数据?

React Router v6 路由跳转传递自定义数据方案

跳转传参写法

navigate 方法的第二个参数支持传入配置对象,自定义数据直接放在配置的state字段内即可:

navigate('/whatever', {
  state: {
    data: yourCustomData // 此处填写需要传递的自定义数据
  }
})

目标组件读取参数

分为两种常用场景:

  • 函数组件直接调用useLocation钩子读取
import { useLocation } from 'react-router-dom'

function TargetComponent() {
  const location = useLocation()
  const passedData = location.state?.data // 已获取传递的自定义数据,可选链用于避免state为空时报错
}
  • 类组件无法直接使用钩子的场景,用withRouter高阶组件包裹后从props取值
import { withRouter } from 'react-router-dom'

class TargetComponent extends React.Component {
  render() {
    const passedData = this.props.location.state?.data
  }
}
export default withRouter(TargetComponent)

注意:和v4版本的逻辑一致,state内的数据仅临时存储在内存中,用户刷新页面后数据会丢失,敏感数据或需要持久化的数据建议通过URL参数、本地存储、全局状态管理方案传递。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 15:48:02