首页 > 解决方案 > 如何在 React Router Dom 的 useHistory 中发送参数?

问题描述

我正在使用 React Router 挂钩进行导航useHistory

导航: history.push("/home", { update: true });

在家里:我正在尝试获取参数 let {update} = useParams();

update始终未定义。这段代码有什么问题。有什么建议么 ?

标签: reactjsreact-hooksreact-router-dom

解决方案


方法中的第二个参数history.push()实际上称为位置状态,

history.push(path, [state])

根据您的要求,您可能希望update作为位置状态或查询字符串的一部分传递。

history.push({
  pathname: '/home',
  search: '?update=true',  // query string
  state: {  // location state
    update: true, 
  },
}); 

如 React-Router文档中所述,您可以通过访问location道具来访问状态。在您的情况下,要获得 的值update

在类组件上,假设它连接到路由器,

this.props.location

对于功能组件,您可以使用useLocation挂钩来访问位置对象。

import { useLocation } from 'react-router-dom';
.
.
const location = useLocation();

console.log(location.state.update)  // for location state
console.log(location.search)  // for query strings;

推荐阅读