Is it possible to match the # part of a route in React Router 4

前端 未结 3 1474
盖世英雄少女心
盖世英雄少女心 2021-02-20 04:04

In my app, I\'d like to match both the path and the hash to different components. For example:

/pageA#modalB

Would show PageA as the main page

3条回答
  •  半阙折子戏
    2021-02-20 04:21

    if you actually want to match and get the parameters, use 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])

提交回复
热议问题