需要在反应中访问头部组件内的url

时间:2017-09-11 17:02:16

标签: reactjs react-router react-router-dom

<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

进行页眉和页脚的路由

3 个答案:

答案 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 

可能就是你要找的东西