【问题标题】:Display URL params on page when using react `withRouter` from react router dom使用来自反应路由器dom的反应`withRouter`时在页面上显示URL参数
【发布时间】:2021-05-07 00:12:40
【问题描述】:

我有一个简单的组件,它将在用户重置密码时显示。

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

当用户重置密码后路由添加了参数时,我想将 url 参数 keyemail 呈现到屏幕上。

通过阅读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,
      },

【问题讨论】:

    标签: javascript reactjs routes react-router-dom


    【解决方案1】:

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

    path: '/password/reset/update/:email/:key',
    

    这可能是问题的原因。

    此外,withRouter 通常用于类组件。鉴于您在这里使用的是功能组件,您可以使用useParams hook

    钩子是用

    导入的
    import { withRouter } from 'react-router-dom';
    

    在这种情况下,将按如下方式使用:

    export const ResetPassword = () => {
        const { email, key } = useParams();
        const text = 'view page';
    

    如果您仍然需要路径名,可以从useLocation hook 获得。

    【讨论】:

    • 感谢您的回复。好的,我一直在阅读文档。我误解了我的本意。我需要query string params 而不是params。如果我理解正确,这些与params 不同,对吗?您的回答已经对我有很大帮助了,不过谢谢...我现在需要弄清楚如何获得queryparams
    • 不用担心。查询字符串参数与 useParams 挂钩返回的参数不同。 React Router 在此处有一个示例,说明如何通过 useLocation 钩子获取查询字符串参数:reactrouter.com/web/example/query-parameters
    猜你喜欢
    • 2022-11-02
    • 1970-01-01
    • 2022-06-25
    • 2021-06-22
    • 1970-01-01
    • 1970-01-01
    • 2021-06-15
    • 1970-01-01
    • 2021-04-23
    相关资源
    最近更新 更多