2017-05-05 36 views
2

有使用參數幾個路線的使用參數的路徑(如/用戶/:用戶,汽車/:汽車/:年) 我試圖避免手動解析location.pathname如果它是可能使用react-router(v3)。賽的反應路由器V3

如何找到與當前網址匹配的路線。 需要類似於:

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

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

更新時間:

它可以通過

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

回答

1

我已經這樣做了使用反應路由器-DOM來實現。我簡化了代碼,以便您可以輕鬆理解它。我只是通過主應用程序組件中的儀表板路由傳遞參數用戶,並在我的子組件中使用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; 

我希望這會幫助你。

+0

尊敬的Rohit,您的回答是正確的。不幸的是不適用於我試圖解決的問題。謝謝 – DraganS

+0

好的@DraganS,沒問題 –