首页 > 解决方案 > 使用来自反应路由器dom的反应`withRouter`时在页面上显示URL参数

问题描述

我有一个简单的组件,当用户重置密码时会显示该组件。

首先,我为组件设置了路由,然后创建了页面(ResetPassword)。

在用户重置密码后,当路由添加了参数时,我想将 url 参数渲染到屏幕key上。email

我认为从阅读文档withRouter中我可以访问matchparams然后是 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,
      },

标签: javascriptreactjsroutesreact-router-dom

解决方案


我在您的路线中看不到定义参数的任何地方。我希望看到类似的东西

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 挂钩中获得。


推荐阅读