使用React阅读当前的完整URL?

reactjs React.js

猿小胖

2020-03-12

如何从ReactJS组件中获取完整的URL?

我想它应该是这样的this.props.location,但它是undefined

第1034篇《使用React阅读当前的完整URL?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

5个回答
小胖Pro 2020.03.12

您可以使用“ document.referrer”访问完整的uri / url

检查https://developer.mozilla.org/en-US/docs/Web/API/Document/referrer

Harry小哥 2020.03.12

如果您需要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"

源:位置路径名属性-W3Schools

如果您尚未使用“反应路由器”,则可以使用以下方法进行安装:

yarn add react-router

然后在“路线”中的React.Component中,您可以调用:

this.props.location.pathname

这将返回路径,不包括域名。

谢谢@ abdulla-zulqarnain!

十三Tony伽罗 2020.03.12

undefined之所以会这么做,因为您可能在React Router之外拥有组件。

请记住,您需要确保要调用this.props.location<Route />组件位于这样的组件内部

<Route path="/dashboard" component={Dashboard} />

然后,在Dashboard组件内部,您可以访问this.props.location...

神奇小小 2020.03.12

window.location.href 是您要寻找的。

Eva猿猿 2020.03.12

this.props.location是react-router功能,如果要使用它,则必须安装。

注意:不返回完整网址。

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android