首页 > 其他 > 详细

只有设置了Route路由的组件,才可以通过this.props.match接受到

时间:2019-12-29 16:03:32      阅读:407      评论:0      收藏:0      [点我收藏+]

项目时,我犯了一个错误。Header我没有设置路由,作为工作组件,然后想在Header组件内部根据路由,隐藏Header,但是因为Header没有用Route包裹,也没有用withRouter,其内部是接受不到this.prop.match,this.prop.location,this.prop.history, 因为这三个属性是父组件Route给他们传递的,而这时候你的Header只是普通组件。

      <Provider store={store}>
                <BrowserRouter>
                    <Header/>
                    <Route exact path="/" component={Home}></Route>
                    <Route exact path="/home" component={Home}></Route>
                    <Route exact path="/login" component={Login}></Route>
                    <Route exact path="/detail/:id" component={Detail}></Route>
                </BrowserRouter>
            </Provider>

正确做法是,将Header也用Route包裹,不用exact精确匹配,这样就匹配任何路由

    <Provider store={store}>
                <BrowserRouter>
                    <Route path="/" component={Header}/>
                    <Route exact path="/" component={Home}></Route>
                    <Route exact path="/home" component={Home}></Route>
                    <Route exact path="/login" component={Login}></Route>
                    <Route exact path="/detail/:id" component={Detail}></Route>
                </BrowserRouter>
            </Provider>

然后就可以在Header内部获取this.props.location, 这里逻辑是如果是login页面,就不显示header头部,返回一个‘’空字符串

if(this.props.location.pathname.indexOf("/login")!==-1){
      return ‘‘
}

只有设置了Route路由的组件,才可以通过this.props.match接受到

原文:https://www.cnblogs.com/shengjunyong/p/12115082.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!