是否可以匹配React Router 4中路由的#部分

时间:2017-02-03 22:24:14

标签: react-router react-router-v4

在我的应用中,我想将路径和哈希匹配到不同的组件。例如:

/pageA#modalB

将PageA显示为主页面,其中modalB位于顶部。 我尝试了以下方法,路径属性有很多变种:

<Route path="#modalB" component={modalB}/>

但没有任何作用。

在模态“控制器”组件内的React Router 2中,我会使用:

browserHistory.listen( (location) => { //do something with loction.hash })

我希望在V4中有更优雅的东西

3 个答案:

答案 0 :(得分:10)

不是开箱即用,但React Router 4的美妙之处在于它自己实现起来非常容易。

let HashRoute = ({ component: Component, path, ...routeProps }) => (
  <Route 
    {...routeProps}
    component={({ location, ...props }) =>
      location.hash === path && <Component {...props} />
    }
  />
)

<HashRoute path="#modalB" component={ModalB} />

答案 1 :(得分:1)

@azium答案可以正常工作,只要您不需要在HashRoute中使用render或child道具即可。 在这种情况下,此解决方案会更好:

import React from 'react';
import { Route } from 'react-router-dom';

const HashRoute = ({ hash, ...routeProps }) => (
  <Route
    render={({ location }) => (
      (location.hash === hash) && <Route {...routeProps} />
    )}
  />
);

export default HashRoute;

像这样使用它:

<HashRoute hash="#modalB" component={ModalB} />

或将其与路线匹配结合:

<HashRoute hash="#modalB" path="/subPageOnly" component={ModalB} />

答案 2 :(得分:1)

如果您确实想匹配并获取参数,请使用matchPath

import { useLocation, matchPath } from 'react-router-dom';

// your route you want to see if it matches
const routePath = '/overtherainbow/:country/#/city/:city/detail'

// somewhere while rendering
const location = useLocation();
useEffect(() => {
  const matched = matchPath(location.pathname + location.hash, routePath);
  if (matched){
    // matched, do something with it, like setting state, fetching data or what not
    console.log(matched.params); // will be {country:..., city:...}
  }
}, [location])