需要在 React 中访问 header 组件内的 url

need to access url inside header component in react

<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 是空的。
我如何访问 url 以及 header 的路由和 react-router 版本 4

的页脚是否正常
window.location.href 

可能就是您要找的东西

您可以使用withRouter函数。

withRouter will re-render its component every time the route changes with the same props as render props: { 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>
  );
}

withRouter() 中包装 Header 然后在 Header 组件中使用:

this.props.location for accessing url
// use WrappedHeader inside Provider
const WrappedHeader = withRouter(Header)
// in Header
this.props.location