如何在没有参数的情况下获取反应路由器原始网址?

pyy*_*ysv 6 javascript reactjs react-router

我想要没有路由器参数的原始 url 路径。

// routers
<Route
  exact
  path={`/users/userDetail/:userId`}
  component={UserDetail}
/>

i want to get string "/users/userDetail" from some components
Run Code Online (Sandbox Code Playgroud)

帮我!

Ale*_*dru 8

您可以使用此钩子从当前路径名中排除所有参数:

import { useLocation, useParams } from 'react-router-dom';

export const useBasePath = () => {
    const location = useLocation();
    const params = useParams<Record<string, string>>();

    return Object.values(params).reduce(
        (path, param) => path.replace('/' + param, ''),
        location.pathname,
    );
};
Run Code Online (Sandbox Code Playgroud)

在您的组件中像这样使用它:

const basePath = useBasePath();

console.log(basePath);
Run Code Online (Sandbox Code Playgroud)


Dac*_*nny 3

如果我理解正确的话,您想要提取当前路由的路径,同时排除userIdURL 的最后一部分 - 假设是这种情况,您可以执行以下操作:

const getCurrentPathWithoutLastPart = () => {

    return location.pathname.slice(0, location.pathname.lastIndexOf('/'))
}
Run Code Online (Sandbox Code Playgroud)

如果您当前的 URL 类似于/users/userDetail/some_value调用该函数将产生/users/userDetail

getCurrentPathWithoutLastPart() // returns /users/userDetail
Run Code Online (Sandbox Code Playgroud)