<Provider store = {store}>
<Router history = {history} >
<section>
<Header/>
<Route exact path="/" component={DealList}/>
<Route path = "/deal" component={FormDeal}/>
<Route path = "/admin" component={Admin}/>
<Footer/>
</section>
</Router>
</Provider>
我想通过我的Header组件访问浏览器的url。但是this.props是空的 我如何访问网址,并使用react-router version-4
进行页眉和页脚的路由答案 0 :(得分:3)
您可以使用withRouter
功能。
withRouter将在每次路径更改时使用与渲染道具相同的道具重新渲染其组件:{match,location,history}。
在你的情况下你可以这样写:
render(){
const HeaderWithRouter = withRouter(Header);
return (
<Provider store = {store}>
<Router history = {history} >
<section>
<HeaderWithRouter/>
<Route exact path="/" component={DealList}/>
<Route path = "/deal" component={FormDeal}/>
<Route path = "/admin" component={Admin}/>
<Footer/>
</section>
</Router>
</Provider>
);
}
答案 1 :(得分:2)
在withRouter()
中包裹标题,然后在标题组件中使用:
this.props.location for accessing url
// use WrappedHeader inside Provider
const WrappedHeader = withRouter(Header)
// in Header
this.props.location
答案 2 :(得分:0)
window.location.href
可能就是你要找的东西