如何从反应路由器的路径中获取变量?

Emb*_*sit 10 javascript ecmascript-6 reactjs react-router-v4

我的反应路由器工作正常..但我想您可以通过日期Path作为title其预期的字符串。

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

谢谢

小智 14

有一个新的api 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()
}

Run Code Online (Sandbox Code Playgroud)


MEn*_*Enf 13

在您的初始组件中,设置加载您的路线的路径。通过将 /: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>
    )
  }
}
Run Code Online (Sandbox Code Playgroud)

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

  • 此解决方案适用于 React-router v4,如果您使用的是版本 5,请参阅下面 Ishan Mujdeci 的回答 (2认同)