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

React Router Dom中如何使用useHistory传递多个对象参数

React useHistory 传递多个参数实现方案

useHistory.push() 方法的第二个参数支持传入自定义state对象,你可以直接在该对象中添加多个需要传递的参数,没有数量限制。

1. 定义需要传递的多个数组

假设你要新增的另一个结构类似的数组名为occupation,示例定义如下:

const gender = [
  { id: 'male', title: 'Male' },
  { id: 'female', title: 'Female' },
  { id: 'other', title: 'Other' },
]
// 新增的第二个数组
const occupation = [
  { id: 'student', title: 'Student' },
  { id: 'worker', title: 'Worker' },
  { id: 'freelancer', title: 'Freelancer' },
]

2. 修改路由跳转逻辑

注意useHistory是React Hooks,只能在组件顶层调用,不要直接在事件回调内执行:

import { useHistory } from 'react-router-dom'

function ParentComponent() {
  // 组件顶层调用hooks获取history实例
  const history = useHistory()

  return (
    <button 
      onClick={() => history.push("/child", { 
        gender, 
        occupation // 新增第二个参数即可
      })}
    >
      跳转到子页面
    </button>
  )
}

3. 子页面获取传递的参数

在/child路由对应的组件中,通过useLocation获取所有传递的state参数:

import { useLocation } from 'react-router-dom'

function ChildComponent() {
  const location = useLocation()
  // 解构获取两个数组,添加默认值避免state为空时报错
  const { gender, occupation } = location.state || {}

  // 后续业务逻辑使用gender和occupation即可
  return <div>子页面内容</div>
}

注意事项

  • 上述用法仅适用于react-router v5版本,v6版本已移除useHistory,替换为useNavigate,用法为navigate("/child", { state: {gender, occupation} })
  • 页面刷新后state会自动丢失,如果需要持久化存储需要配合localStorage等方案实现

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 12:15:09