Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在没有参数的情况下获取路由器源url?_Javascript_Reactjs_React Router - Fatal编程技术网

Javascript 如何在没有参数的情况下获取路由器源url?

Javascript 如何在没有参数的情况下获取路由器源url?,javascript,reactjs,react-router,Javascript,Reactjs,React Router,我想创建没有路由器参数的源url路径 // routers <Route exact path={`/users/userDetail/:userId`} component={UserDetail} /> i want to get string "/users/userDetail" from some components //路由器 我想从一些组件中获取字符串“/users/userDetail” 救救我 如果我理解正确,您希望提取当前路由的路径,同时排除U

我想创建没有路由器参数的源url路径

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

i want to get string "/users/userDetail" from some components
//路由器
我想从一些组件中获取字符串“/users/userDetail”

救救我

如果我理解正确,您希望提取当前路由的路径,同时排除URL的最后一个
userId
部分-假设是这样,您可以执行以下操作:

const getCurrentPathWithoutLastPart = () => {

    return location.pathname.slice(0, location.pathname.lastIndexOf('/'))
}
如果当前URL类似于
/users/userDetail/some\u值
,则调用该函数将生成
/users/userDetail

getCurrentPathWithoutLastPart() // returns /users/userDetail

现有的解决方案是有帮助的,但并不适用于所有场景。例如,我们不能将其用作父路径名,因为它将返回空字符串

向现有解决方案中添加:

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

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

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,
    );
};
const basePath = useBasePath();

console.log(basePath);