javascript - 使用来自反应路由器dom的反应`withRouter`时在页面上显示URL参数
问题描述
我有一个简单的组件,当用户重置密码时会显示该组件。
首先,我为组件设置了路由,然后创建了页面(ResetPassword)。
在用户重置密码后,当路由添加了参数时,我想将 url 参数渲染到屏幕key
上。email
我认为从阅读文档withRouter
中我可以访问match
,params
然后是 url 中的键,然后将它们呈现到屏幕上。然而,这是行不通的。
知道为什么吗?
这是我的代码:
// @flow
import React from 'react';
import { compose } from 'ramda';
import { withRouter } from 'react-router-dom';
import Helmet from 'react-helmet';
import featureRoute from '../components/Decorators/featureRoute';
type Props = {
match: {
params: {
email: string,
key: any
}
},
location: {
pathname: string
}
};
export const ResetPassword = ({
match: {
params: { email, key }
},
location: { pathname }
}: Props) => {
const text = 'view page';
return (
<>
<Helmet title="Page title" titleTemplate="%s" />
<div className="p-page">
<div>{text}</div>
<div>{email}</div>
<div>{key}</div>
<div>{pathname}</div>
</div>
</>
);
};
export default compose(
featureRoute(),
withRouter
)(ResetPassword);
路线
{
component: ResetPassword,
path: '/password/reset/update',
exact: true,
},
解决方案
我在您的路线中看不到定义参数的任何地方。我希望看到类似的东西
path: '/password/reset/update/:email/:key',
这可能是问题的原因。
此外,withRouter
通常用于类组件。鉴于您在这里使用的是功能组件,您可以使用useParams 钩子。
钩子是用进口的
import { withRouter } from 'react-router-dom';
对于这种情况,将按如下方式使用:
export const ResetPassword = () => {
const { email, key } = useParams();
const text = 'view page';
如果您仍然需要路径名,可以从useLocation 挂钩中获得。
推荐阅读
- php - PHP:无法更改子类中同名静态函数中的参数数量
- php - 即使我添加了名称,HTML 表单也不起作用
- spring-boot - 具有 @ManyToMany 属性的 JPA 规范
- blazor - Blazor 显示名称
- sql - SQL 服务器管理连接/关联
- python - 如何比较熊猫中的两个数据框
- python - 来自 python 中的 c 函数的错误返回值
- sql - 是否可以使用另一个 select 语句的结果创建一个 select 语句?
- purescript - 未找到类型类实例,实例头包含未知类型变量
- python - 我是否以正确的方式管理 asyncio 任务(python 3.9)?