如何从反应路由器的路径中获取变量?
How can I get a variable from the path in react router?
我的反应路由器工作正常..但我想从 Path
获取日期作为 title
需要一个字符串。
<Route exact path="/meeting/:date"
breadcrumb="Meetings"
title={DATE}
component={(props) => (
<FooComponent
date={props.match.params.date} />
)}
/>
谢谢
我为此使用 Helmet,它允许您更新标题、元数据、脚本以及基本上与 header 相关的所有内容。
安装后,只需将以下代码添加到 FooComponent
或常见的 parent 组件即可。
<Helmet>
<title>{props.match.params.date}</title>
</Helmet>
在您的初始组件中,设置加载路线的路径。通过将 /:date 添加到路由的末尾,可以通过在该路由组件内调用 props.match.params.date 来访问该字符串。
<Route exact path="/meeting/:date" component={DateComponent} />
在路由呈现的组件中,使用 props.match.params.date
从路径
访问您的字符串
Class DateComponent extends React.Component{
render(){
return(
<h2>{this.props.match.params.date}</h2>
)
}
}
在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()
}
我的反应路由器工作正常..但我想从 Path
获取日期作为 title
需要一个字符串。
<Route exact path="/meeting/:date"
breadcrumb="Meetings"
title={DATE}
component={(props) => (
<FooComponent
date={props.match.params.date} />
)}
/>
谢谢
我为此使用 Helmet,它允许您更新标题、元数据、脚本以及基本上与 header 相关的所有内容。
安装后,只需将以下代码添加到 FooComponent
或常见的 parent 组件即可。
<Helmet>
<title>{props.match.params.date}</title>
</Helmet>
在您的初始组件中,设置加载路线的路径。通过将 /:date 添加到路由的末尾,可以通过在该路由组件内调用 props.match.params.date 来访问该字符串。
<Route exact path="/meeting/:date" component={DateComponent} />
在路由呈现的组件中,使用 props.match.params.date
从路径
Class DateComponent extends React.Component{
render(){
return(
<h2>{this.props.match.params.date}</h2>
)
}
}
在react-router-dom 5.1
https://github.com/ReactTraining/react-router/releases/tag/v5.1.0
import {useParams} from "react-router-dom";
function MyComponent(){
const {date} = useParams()
}