如何在React应用程序中读取当前URL

时间:2018-08-23 15:04:21

标签: javascript reactjs

我想在react应用程序中读取并打印当前URL。现在,我正在使用“ window.location.pathname”读取URL,但想知道是否有更好的方法或某些反应方法来读取URL

4 个答案:

答案 0 :(得分:4)

window.location.href

返回当前页面的href(URL)

window.location.hostname

返回虚拟主机的域名

window.location.pathname

返回当前页面的路径和文件名

window.location.protocol

返回使用的Web协议(http:或https:)

答案 1 :(得分:1)

如果您使用的是React Router,并且您的组件由Route呈现,如下所示:

<Route exact path='/' component={HomeComponent}/>

该组件将自动从Route分别接收名为historylocationmatch的三个对象。这样一来,您可以在location.pathname下找到您要的内容。更多信息here

如果您仍在使用React Router,并且您的组件未使用Route进行渲染,则需要使用withRouter,它是一个HOC,将为您提供history,{{1 }}和location作为组件的道具。更多信息here

如果您不使用反应路由器,则需要使用matchwindow.location.pathname或仅使用window.location.href

答案 2 :(得分:0)

如果您使用反应路由器:

const currentRoute= this.props.location.pathname

否则,您可以这样获得:

const currentRoute= window.location.pathname

href将为您提供完整的网址。

答案 3 :(得分:0)

我们可以使用 react-router-dom 包中的 withRouter 组件从 this.props 获取它,方法如下:添加到类中

import React from 'react';

import { connect } from 'react-redux';
import { Switch, Route, withRouter } from 'react-router-dom';


class Application extends React.PureComponent {
  
  render() {
    console.log(this.props)
    this.props.location.pathname // we will get the pathname

    return (
      <div className='application'>
        {Hi}
      </div>
    );
  }
}


export default connect(mapStateToProps, actions)(withRouter(Application));

输出:

enter image description here

相关问题