Javascript 如何在没有参数的情况下获取路由器源url?
我想创建没有路由器参数的源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
// 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);