我如何从一个ReactJS组件中获得完整的URL ?
我认为它应该是这样的。props。location但它是未定义的
我如何从一个ReactJS组件中获得完整的URL ?
我认为它应该是这样的。props。location但它是未定义的
当前回答
location是一个react-router特性,如果你想使用它,你必须安装它。
注意:不返回完整的url。
其他回答
Window.location.href是你要找的。
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
为了获得当前路由器实例或当前位置,你必须从react-router-dom中使用withRouter创建一个高级组件。否则,当你试图访问this.props.location时,它将返回undefined
例子
import React, { Component } from 'react';
import { withRouter } from 'react-router-dom';
class className extends Component {
render(){
return(
....
)
}
}
export default withRouter(className)
如果你需要URL的完整路径,你可以使用Javascript:
window.location.href
要获得路径(减去域名),你可以使用:
window.location.pathname
console.log (window.location.pathname);//输出:"/js"(代码段运行的地方) console.log (window.location.href);/ /收益率:“https://stacksnippets.net/js”
来源:位置路径名属性- W3Schools
如果你还没有使用"react-router",你可以使用以下方法安装它:
纱线添加反应路由器
然后在React中。组件,你可以调用:
this.props.location.pathname
这将返回路径,不包括域名。
谢谢@abdulla-zulqarnain !