【问题标题】:Match the route with params by react-router v3通过 react-router v3 将路由与参数匹配
【发布时间】:2017-10-03 08:18:54
【问题描述】:

有几条带参数的路线(例如./user/:user, car/:car/:year) 如果可以使用 react-router (v3),我会尽量避免手动解析 location.pathname

如何找到与当前 url 位置匹配的路由。 需要类似的东西:

if (router.match_to_route('/user/:user')) {
   ... do something
}
...

https://github.com/ReactTraining/react-router/blob/v3/modules/matchRoutes.js 中的 matchRoutes 方法可能是我需要的方法。 谢谢。

更新:

可以通过

import { match } from 'react-router';

const routes = router.routes;
match({ routes, location }, (error, redirect, renderProps) => {
   const listOfMatchingRoutes = renderProps.routes;
   if (listOfMatchingRoutes.some(route => route.path === '/user/:user')) {
      ...
   }
}

https://github.com/ReactTraining/react-router/issues/3312#issuecomment-299450079

【问题讨论】:

    标签: javascript reactjs react-router


    【解决方案1】:

    我已经使用 react-router-dom 完成了这项工作。我简化了代码,以便您可以轻松理解它。我刚刚在主 App 组件中通过我的仪表板路由传递了 param 用户,并在名为 Dashboard 的子组件中使用 this.props.match.params.user 访问它。

    App.js 文件

    class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = {open: false};
        this.state = {message: "StackOverflow"};
      }
    
    render(){
        return (
            <Router>
              <div>
    
                <Route exact path="/dashboard/:user" render={props => <Dashboard {...props} />} />
                <Route exact path="/information" render={props => <Information {...props} />} />
              </div>
            </Router>
        );
     }
    }
    

    Dashboard.js

    import React from 'react';
    
    
    class Dashboard extends React.Component {
    
      constructor(props) {
        super(props);
      }
    
      render() {
    
        return (
                <div ><h1> Hello {this.props.match.params.user}</h1></div>
        );
      }
    }
    
    export default Dashboard;
    

    希望对你有帮助。

    【讨论】:

    • 亲爱的 Rohit,您的回答是正确的。不幸的是不适用于我要解决的问题。谢谢
    • 好的@DraganS,没问题
    【解决方案2】:

    在 RR4 上你可以使用matchPath

    const match =  routes.find(route) => matchPath(props.location.pathname, {
        path: route.path,
        exact: true,
        strict: false
      })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-02
      • 1970-01-01
      • 2016-09-13
      • 1970-01-01
      • 2016-04-22
      • 1970-01-01
      • 2015-03-20
      • 2018-06-15
      相关资源
      最近更新 更多