获取react-router的当前路由

Rol*_*and 6 javascript reactjs react-router

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

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

我试过这个:

    const match = useRouteMatch({
        path: location.pathname,
        strict: true,
        sensitive: true
    });
Run Code Online (Sandbox Code Playgroud)

但它没有给我道具。

所以我需要类似的东西:

    const match = useRouteMatch({
        path: `/:lang/:car`,
        strict: true,
        sensitive: true
    });
Run Code Online (Sandbox Code Playgroud)

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

我还尝试使用useParams中的react-router-dom. 并做类似的事情:

const { lang } = useParams<ParamTypes>();
Run Code Online (Sandbox Code Playgroud)

如果我将其写在主组件App.tsx中,这也不起作用。/:lang仅在其路线中明确存在的组件中。

如果这还不清楚,我会举一个例子。

假设我有这些路线:

<Route path='/'/>
<Route path='/:lang'/>
<Route path='/:lang/:bookId'/>
<Route path='/:lang/:bookId/:author'/>
Run Code Online (Sandbox Code Playgroud)

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

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

我应该有类似的东西:

    const match = useRouteMatch({
        path: `/:lang/:bookId`,
        strict: true,
        sensitive: true
    });
Run Code Online (Sandbox Code Playgroud)

但是假设我输入 url baseurl/en/21/some-name,那么matchconst 将为空。在这种情况下,我也想得到author. 但是我不知道用户将输入什么网址。所以这就是为什么我需要动态获取路线。

Dre*_*ier 3

尝试这个:

  const findPath() {
    const location = useLocation();
    useEffect(() => {
      const currentPath = location.pathname;
    }, [location]);
    return currentPath;
  }
Run Code Online (Sandbox Code Playgroud)

这将使用 useLocation 挂钩返回整个路径,并且每次 url 由于 useEffect 而更改时都会重新渲染。

  • 这不会做任何事情,因为它充满了错误...... (4认同)