我想在React应用程序中阅读并打印当前的URL。目前,我正在使用“window.location.pathname”来读取URL,但我想知道是否有更好的方法或一些React方式来读取URL。
我想在React应用程序中阅读并打印当前的URL。目前,我正在使用“window.location.pathname”来读取URL,但我想知道是否有更好的方法或一些React方式来读取URL。
http://localhost:3000/question
。window.location.href
window.location.hostname
window.location.host
返回 localhost:3000
window.location.pathname
返回当前页面的路径和文件名(/question
)
window.location.origin
返回http://localhost:3000
window.location.protocol
http:
)
window.location.port
3000
localhost:8080
),请使用window.location.host
,参见https://dev59.com/wmw15IYBdhLWcg3wisS-#6549132。 - Alexandre DuBreuil如果你正在使用React Router,而且你的组件是由一个像下面这样的Route
渲染的:
<Route exact path='/' component={HomeComponent}/>
const currentRoute= this.props.location.pathname
const currentRoute= window.location.pathname
href会给你完整的url。
useLocation
和useHistory
钩子。import { useHistory ,useLocation } from 'react-router-dom';
const location = useLocation()
console.log(location.pathname)
const history = useHistory()
console.log(history.location.pathname)
您可以使用useParams
钩子来访问URL中的值。在App.jsx中创建路由时,您将像这样指定输入变量的名称:
<Route
path="/search/:searchType/:module/:category/:search/:source"
exact={true}
component={yourComponent}
/>
然后你可以在组件内使用useParams
钩子来访问变量的值。
const {searchType, module, category, search, source} = useParams();
我们可以通过在类中添加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));
输出: