【问题标题】:Is it possible to match the # part of a route in React Router 4是否可以匹配 React Router 4 中路由的 # 部分
【发布时间】:2017-02-03 22:24:14
【问题描述】:

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

/pageA#modalB

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

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

但没有任何效果。

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

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

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

【问题讨论】:

    标签: react-router react-router-v4


    【解决方案1】:

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

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

    【讨论】:

    • 非常干净。我也通过使用 withRouter 来工作。 reacttraining.com/react-router/#withrouter
    • 如果你在你的哈希中使用了任何奇怪的字符,你必须解码URI(location.hash),否则它不会正确匹配。
    【解决方案2】:

    只要您不需要在 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} />
    

    【讨论】:

      【解决方案3】:

      如果你真的想匹配并获取参数,请使用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])

      【讨论】:

      • 所以匹配算法可以处理#,只是react-router默认单独使用location.pathname?在# 之前和/或之后有斜线是否重要?会说'/overtherainbow/:country#:city/detail 也可以吗?
      • 是的,应该可以工作 - 您想要的任何路径(受诸如 :country 之类的占位符限制,如 react-router 文档中所述)
      猜你喜欢
      • 2020-01-22
      • 2018-06-07
      • 2023-02-17
      • 2016-09-02
      • 2021-04-16
      • 1970-01-01
      • 2017-06-12
      • 1970-01-01
      • 2017-08-11
      相关资源
      最近更新 更多