简体   繁体   English

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

[英]how get react router origin url without params?

I want to origin url path without router params.我想要没有路由器参数的原始 url 路径。

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

i want to get string "/users/userDetail" from some components

help me!帮我!

If I understand correctly, you want to extract the path of the current route, while excluding the last userId part of the URL - assuming that's the case, you could do the following:如果我理解正确,您想提取当前路由的路径,同时排除 URL 的最后一个userId部分 - 假设是这种情况,您可以执行以下操作:

const getCurrentPathWithoutLastPart = () => {

    return location.pathname.slice(0, location.pathname.lastIndexOf('/'))
}

If your current URL is something like /users/userDetail/some_value calling the function will yield /users/userDetail :如果您当前的 URL 类似于/users/userDetail/some_value调用该函数将产生/users/userDetail

getCurrentPathWithoutLastPart() // returns /users/userDetail

You can exclude all params from current pathname by using this hook:您可以使用此钩子从当前路径名中排除所有参数:

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,
    );
};

Use it like this in your component:在您的组件中像这样使用它:

const basePath = useBasePath();

console.log(basePath);

The existing solution is helpful, but it doesn't work for all scenarios.现有的解决方案很有帮助,但并不适用于所有场景。 For example, we can't use it for the parent pathname as it will return empty string.例如,我们不能将它用于父路径名,因为它会返回空字符串。

Adding to the existing solution:添加到现有解决方案:

const getCurrentPathWithoutLastPart = () => {
    const pathRgx = /\//g;
    const childroutecount = ((location.pathname || '').match(pathRgx) || []).length
    return childroutecount > 1 ? location.pathname.slice(0, location.pathname.lastIndexOf('/')) : location.pathname;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM