我如何从一个ReactJS组件中获得完整的URL ?

我认为它应该是这样的。props。location但它是未定义的


当前回答

只是在这个页面上添加一些进一步的文档-我已经与这个问题斗争了一段时间。

如上所述,获取URL的最简单方法是通过window.location.href。

然后,我们可以使用let urlElements = window.location.href.split('/')通过普通Javascript提取部分URL。

然后我们将console.log(urlElements)查看通过在URL上调用.split()生成的元素数组。

一旦找到想要访问数组中的哪个索引,就可以将其赋值给一个变量

let urlElelement = (urlElements[0])

现在你可以使用urlElement的值,它将是URL的特定部分,无论你想在哪里。

其他回答

你得到的是未定义的,因为你可能有React路由器之外的组件。

记住,你需要确保调用this.props.location的组件位于<Route />组件中,如下所示:

<Route path="/仪表盘"抱怨={仪表盘}/>

然后在Dashboard组件中,你可以访问this.props.location…

只是在这个页面上添加一些进一步的文档-我已经与这个问题斗争了一段时间。

如上所述,获取URL的最简单方法是通过window.location.href。

然后,我们可以使用let urlElements = window.location.href.split('/')通过普通Javascript提取部分URL。

然后我们将console.log(urlElements)查看通过在URL上调用.split()生成的元素数组。

一旦找到想要访问数组中的哪个索引,就可以将其赋值给一个变量

let urlElelement = (urlElements[0])

现在你可以使用urlElement的值,它将是URL的特定部分,无论你想在哪里。

location是一个react-router特性,如果你想使用它,你必须安装它。

注意:不返回完整的url。

Window.location.href是你需要的。但是如果你正在使用react路由器,你可能会发现检查useLocation和useHistory钩子很有用。 这两种方法都创建了一个具有pathname属性的对象,你可以读取它,而且对很多其他事情都很有用。这是一个youtube视频,解释了react路由器钩子

两者都会给你你所需要的(没有域名):

import { useHistory ,useLocation } from 'react-router-dom';
const location = useLocation()
location.pathname

const history = useHistory()
history.location.pathname

普通JS:

window.location.href // Returns full path, with domain name
window.location.origin // returns window domain url Ex : "https://stackoverflow.com"
window.location.pathname // returns relative path, without domain name

使用react-router

this.props.location.pathname // returns relative path, without domain name

使用react Hook

const location = useLocation(); // React Hook
console.log(location.pathname); // returns relative path, without domain name