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

7

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


如果您正在使用路由器,可以查看此链接 https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/withRouter.md - SGhaleb
6个回答

22
假设当前的URL是http://localhost:3000/question
window.location.href

返回当前页面的href(URL)(http://localhost:3000/question)
window.location.hostname

返回Web主机的域名(localhost)
window.location.host

返回 localhost:3000


window.location.pathname

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


window.location.origin

返回http://localhost:3000


window.location.protocol

返回使用的网络协议(http: 或 https:)(在这种情况下返回 http:
window.location.port

返回 3000

1
如果您想要带有端口号的主机名(例如localhost:8080),请使用window.location.host,参见https://dev59.com/wmw15IYBdhLWcg3wisS-#6549132。 - Alexandre DuBreuil

4

如果你正在使用React Router,而且你的组件是由一个像下面这样的Route渲染的:

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

那个组件会自动从名为“history”,“location”和“match”的中获得三个对象,你可以在“location.pathname”下找到你想要的内容。更多信息在这里
如果你仍在使用react router,并且你的组件没有被渲染与,那么你需要使用withRouter,它是一个HOC,并将把“history”,“location”和“match”作为props给你的组件。更多信息在这里
如果你没有使用react router,你需要使用“window.location.pathname”或“window.location.href”或只有“location.pathname”。

1
如果您正在使用React Router:

const currentRoute= this.props.location.pathname

否则,您可以像这样获取它:
const currentRoute= window.location.pathname

href会给你完整的url。


0
如果你正在使用React JS,那么请使用useLocationuseHistory钩子。
import { useHistory ,useLocation } from 'react-router-dom';
const location = useLocation()
console.log(location.pathname)

const history = useHistory()
console.log(history.location.pathname)

0

您可以使用useParams钩子来访问URL中的值。在App.jsx中创建路由时,您将像这样指定输入变量的名称:

<Route 
   path="/search/:searchType/:module/:category/:search/:source"
   exact={true}
   component={yourComponent}
/>

然后你可以在组件内使用useParams钩子来访问变量的值。

const {searchType, module, category, search, source} = useParams();

0

我们可以通过在类中添加withRouter组件来从react-router-dom包中以以下方式使用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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接