如何在路由器外访问`match.params`?

How to access `match.params` outside of router?

我正在尝试为我的应用程序的容器获取 match.params

我试过使用 withRouter(AppContainer),但 match.params 总是空的。

// Routes
import React from 'react';
import { Route, Switch, Router } from 'react-router';
import { createBrowserHistory} from 'history';
import AppContainer from './app-container';
...
<Router history={createBrowserHistory()}>
  <AppContainer>
    <Switch>
      ...
      <Route exact path="/:path1/:path2" component={() => <div>hello</div>} />
      ...
    </Switch>
  </AppContainer>
</Router>

// app-container.js
import React from 'react';
import { withRouter } from 'react-router';
const AppContainer = (props) => {
  const { match } = props;
  console.log(match.params); // This will always be empty
  return <div>whatever</div>;
};
export default withRouter(AppContainer);

导航到 /foo/bar。 我希望 AppContainer 中的 match.params{ path1: 'foo', path2: 'bar'},但它们总是 {}.

我认为这是因为 AppContainer 在具有我感兴趣的路由参数的路由之外。

所以,我想知道我是否可以在这里做另一种方法,以便我可以在 AppContainer 中获取路由参数。理想情况下不使用 redux 存储。

总之没办法用match.

在我看来,唯一的方法是使用 matchPath

import { matchPath, withRouter } from 'react-router';

const Test = ({ location }) => {
  /*
  `matchPath` will return `null` if it doesn't match the path format.
  If it matches, it will return some object with parameters put into it
  nicely like `match.params`.
  */
  matchPath(location.search, { path: '/:path1/:path2' });
};
export default withRouter(Test);

如果有人正在寻找如何使用钩子解决这个问题,您可以简单地使用 useRouteMatch() 钩子。甚至更干净了。

import {useRouteMatch} from 'react-router-dom';

const Test = () => {

const { params } = useRouteMatch('/:path1/:path2');

}