簡體   English   中英

通過react-router v3將路由與params匹配

[英]Match the route with params by react-router v3

有幾個帶params的路由(比如./ user /:user,car /:car /:year)我試圖避免手動解析location.pathname如果可以使用react-router(v3)的話。

如何找到與當前網址匹配的路由。 需要類似的東西:

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

我使用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;

我希望它會對你有所幫助。

在RR4上,您可以使用matchPath

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM