首页 > 解决方案 > 如何在没有参数的情况下获得反应路由器原始网址?

问题描述

我想在没有路由器参数的情况下生成 url 路径。

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

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

帮我!

标签: javascriptreactjsreact-router

解决方案


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

const getCurrentPathWithoutLastPart = () => {

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

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

getCurrentPathWithoutLastPart() // returns /users/userDetail

推荐阅读