最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - how get react router origin url without params? - Stack Overflow

programmeradmin2浏览0评论

I want to origin url path without router params.

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

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

help me!

I want to origin url path without router params.

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

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

help me!

Share Improve this question asked Apr 5, 2019 at 0:36 pyyyyysvpyyyyysv 1,0072 gold badges8 silver badges7 bronze badges
Add a comment  | 

5 Answers 5

Reset to default 10

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

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:

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:

getCurrentPathWithoutLastPart() // returns /users/userDetail

The answer from Alecu Marian Alexandru does work for most routes but fails for a special case. If you got a path parameter that is a substring of the route path like:

/category/cat

you'll get

egory/cat

I fixed this by deconstructing the "path parameter string" and "location.pathname string" into arrays and filtering out every path parameter from the location.pathname array:

    export function useRoutePath()
    {
       const location = useLocation();
       const params = useParams<Record<string, string>>()["*"]?.split("/").filter(param => param.length);
       const pathElements = location.pathname.split("/").filter(element => element.length && !params?.includes(element));
       return "/" + pathElements.join("/");
    }

Here is my solution hope it helps

export const useRouterPath = () => {
  const location = useLocation();
  const params = useParams<Record<string, string>>();
  return Object.keys(params).reduce((path, param) => {
    const decodedpath = decodeURIComponent(path);
    const replaced = decodedpath.replace("/" + params[param], "");
    return replaced;
  }, location.pathname);
};

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;
}
发布评论

评论列表(0)

  1. 暂无评论