【问题标题】:How can I get a variable from the path in react router?如何从反应路由器的路径中获取变量?
【发布时间】:2018-06-13 13:50:11
【问题描述】:

我的反应路由器工作正常.. 但我想从 Path 获取日期作为 title 需要一个字符串。

  <Route exact path="/meeting/:date"
              breadcrumb="Meetings"
              title={DATE}
              component={(props) => (
                <FooComponent
                  date={props.match.params.date} />
              )}
            />

谢谢

【问题讨论】:

  • 如果您使用 v4,正如我在文档中所见,您可以提取 url 参数的唯一位置是在包装组件中,例如您在 FooComponent 中使用的。你能分享标题作为路线道具的目的吗?也许您应该将标题逻辑替换到其他地方。

标签: javascript reactjs ecmascript-6 react-router-v4


【解决方案1】:

react-router-dom 5.1中有一个新的api

https://github.com/ReactTraining/react-router/releases/tag/v5.1.0

import {useParams} from "react-router-dom";

function MyComponent(){
    const {date} = useParams()
}

【讨论】:

    【解决方案2】:

    在您的初始组件中,设置加载您的路线的路径。通过将 /:date 添加到路由的末尾,可以通过在该路由组件中调用 props.match.params.date 来访问该字符串。

    &lt;Route exact path="/meeting/:date" component={DateComponent} /&gt;

    在路由渲染的组件中,使用props.match.params.date从路径访问你的字符串

    Class DateComponent extends React.Component{
      render(){
        return(
          <h2>{this.props.match.params.date}</h2>
        )
      }
    }
    

    https://reacttraining.com/react-router/web/api/match

    【讨论】:

    • 此解决方案适用于 React-router v4,如果您使用的是版本 5,请参考下面 Ishan Mujdeci 的回答
    【解决方案3】:

    我为此使用Helmet,它允许您更新标题、元数据、脚本以及基本上与标题相关的任何内容。

    安装后,只需将以下代码添加到FooComponent 或公共父组件。

    <Helmet>
      <title>{props.match.params.date}</title>
    </Helmet>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-17
      • 2016-06-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多