如何从ReactJS组件中获取完整的URL?
我觉得应该像this.props.location,但它是undefined
发布于 2016-10-03 02:14:21
window.location.href是你要找的东西。
发布于 2018-10-10 04:30:46
如果需要URL的完整路径,可以使用普通Javascript:
window.location.href
要获得路径(减去域名),可以使用:
window.location.pathname
console.log(window.location.pathname); //yields: "/js" (where snippets run)
console.log(window.location.href); //yields: "https://stacksnippets.net/js"
如果您还没有使用“react路由器”,则可以使用以下方法安装:
yarn add react-router
然后,在“路由”内的React.Component中,您可以调用:
this.props.location.pathname
这将返回路径,不包括域名。
谢谢阿不都拉-祖尔卡南!
发布于 2020-09-26 01:40:10
window.location.href是你所需要的。但是,如果您使用的是react路由器,您可能会发现查看、useLocation、和useHistory钩子很有用。这两种方法都创建了一个具有路径名属性的对象,您可以读取该属性,并且对于其他一些东西都很有用。这里有一段youtube视频解释了路由器钩子的反应
两者都会给你所需要的(没有域名):
import { useHistory ,useLocation } from 'react-router-dom';
const location = useLocation()
location.pathname
const history = useHistory()
history.location.pathnamehttps://stackoverflow.com/questions/39823681
复制相似问题