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

时间:2019-03-28 03:26:13

标签: react-router-v4

我正在尝试为我的应用容器获取char a1[] = {'R', 'A', 'D', 'A', 'K'}; boolean isPalindrome=true; for (int i = 0; i < a1.length-1; i++) { for (int j = a1.length-1; j >=0; j--) { if(a1[i]==a1[j]) isPalindrome=true; else isPalindrome=false; } } System.out.println(isPalindrome);

我尝试使用;with installed as ( select PACK from software where TAGNUM in ( select tagnum from PC where comp in ( select comp from computer where MFRNAME = 'HP'))) select * from Package p left join installed i on p.pack = i.pack where i.pack is null ,而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/barmatch.params,但它们始终是AppContainer

我认为这是因为{ path1: 'foo', path2: 'bar'}不在我感兴趣的具有路线参数的路线之外。

因此,我想知道是否还有另一种方法可以在{}中获取路由参数。理想情况下,不使用Redux存储。

2 个答案:

答案 0 :(得分:3)

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

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

const Test = () => {

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

}

答案 1 :(得分:0)

简而言之,无法使用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);