reactjs - 如何在 React Router Dom 的 useHistory 中发送参数?
问题描述
我正在使用 React Router 挂钩进行导航useHistory
。
导航: history.push("/home", { update: true });
在家里:我正在尝试获取参数 let {update} = useParams();
但update
始终未定义。这段代码有什么问题。有什么建议么 ?
解决方案
方法中的第二个参数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;
推荐阅读
- java - 有没有办法遍历 ListView 的所有子视图并将它们转换为 TextView
- google-apps-script - 在 Google Apps 脚本的自定义函数中添加前导零
- powershell - 如何阻止 PSReadLine 在 powershell 7.1.3 中更改光标?
- javascript - 使用纯 javascript 从外部网站获取信息
- ios - SFDC - 使用 Forcereact 反应本机项目 - 不工作
- javascript - Break 语句不起作用。它返回答案 50 两次。一旦条件为真并第一次打印,有没有办法突破?
- javascript - 如何将 UTC 时间转换和格式化为本地和 dd/mmm/yyyy hh:mm javascrpt
- c - STM BlueNRG-MS 最大特征长度
- javascript - 为什么从 Firefox 浏览器访问时,现场时间数据没有保存在数据库中?
- python - 如何使用 Selenium.click