获取反应路由器的当前路由

时间:2020-10-11 22:57:28

标签: javascript reactjs react-router

如何获取当前路线?我的意思是路线,而不是路径

手动输入网址后,在我的应用程序 App.tsx 的根组件中,我想从网址中获取一些选项

我尝试过:

    const match = useRouteMatch({
        path: location.pathname,
        strict: true,
        sensitive: true
    });

但是它没有给我道具。

所以我需要类似的东西:

    const match = useRouteMatch({
        path: `/:lang/:car`,
        strict: true,
        sensitive: true
    });

但是我需要以某种方式动态获取该路径(路由)。

我还尝试使用react-router-dom中的 useParams 。并执行类似的操作:

const { lang } = useParams<ParamTypes>();

如果我在主要组件 App.tsx 中编写它,这也将不起作用。仅在路由中明确包含/:lang的组件中。

如果不清楚,我将举一个例子。

假设我有以下路线:

<Route path='/'/>
<Route path='/:lang'/>
<Route path='/:lang/:bookId'/>
<Route path='/:lang/:bookId/:author'/>

然后我手动输入网址baseurl/en/21

App.tsx 中,如何获取lang和bookId?

我应该有类似的东西

    const match = useRouteMatch({
        path: `/:lang/:bookId`,
        strict: true,
        sensitive: true
    });

但是说我输入网址baseurl/en/21/some-name,那么match常量将为空。在这种情况下,我也想获得author。但是我不知道用户将输入什么网址。所以这就是为什么我需要动态获取路线的原因。

1 个答案:

答案 0 :(得分:0)

尝试一下:

  const findPath() {
    const location = useLocation();
    useEffect(() => {
      const currentPath = location.pathname;
    }, [location]);
    return currentPath;
  }

这将使用useLocation钩子返回整个路径,并且由于useEffect每次更改URL时都会重新呈现。

相关问题