只有設置了Route路由的組件,才可以通過this.props.match接受到


項目時,我犯了一個錯誤。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包裹

    <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,我們即可以根據需要來返回Header內容還是‘’空字符串

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM