13

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

/pageA#modalB

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

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

但没有任何效果。

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

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

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

4

3 回答 3

16

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

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

<HashRoute path="#modalB" component={ModalB} />
于 2017-02-03T23:48:35.840 回答
6

只要您不需要在 HashRoute 中使用渲染或儿童道具,@azium 答案就可以正常工作。在这种情况下,此解决方案将更好地工作:

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} />
于 2018-12-20T12:09:22.233 回答
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])

于 2020-06-30T08:29:39.190 回答