如何在 React Router Dom 的 useHistory 中发送参数? [英] How to send params in useHistory of React Router Dom?

查看:292
本文介绍了如何在 React Router Dom 的 useHistory 中发送参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 React Router 钩子进行导航 useHistory.

I am using React Router hooks for navigation useHistory.

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

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

In home : I am trying to get params let {update} = useParams();

但是 update 总是未定义的.这段代码有什么问题.有什么建议吗?

But update is always undefined. Whats wrong with this code. Any suggestions ?

推荐答案

history.push() 方法中的第二个参数其实就是所谓的位置状态,

The second parameter in the history.push() method is actually known as the location state,

history.push(path, [state])

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

Depending on your requirements, you may want to pass update as part of the location state, or the query string.

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

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

As stated on the React-Router documentation, you can access the state by accessing the location props. In your case, to get the value for update,

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

On class components, assuming that it is connected to the router,

this.props.location

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

For functional components, you can use the useLocation hook to access the location object.

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

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

这篇关于如何在 React Router Dom 的 useHistory 中发送参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆