簡體   English   中英

React-router嵌套帶有history.push的路由

[英]React-router nested routes with history.push

我有一個反應頁面,可根據當前路線呈現登錄頁面或導航欄+容器組件。 我不希望導航欄在登錄頁面中可見。 因此,我的應用程序的結構如下:

index.js

ReactDOM.render(<Main/>, document.getElementById('root'));

Main.js

<Router>
  <Switch>
    <Route path="/login" component={Login} />
    <PrivateRoute path="/" component={App} />
  </Switch>
</Router>

App.js

<Router>
  <div className="App">
    <Navbar/>
    <div className="main-container">
      <Switch>
        <Route exact path="/" component={Container1}/>
        <Route path="/route1" component={Container2}/>
        <Route path="/route2" component={Container3}/>
      </Switch>
    </div>
  </div>
</Router>

現在,如果要在任何Container組件內部執行this.props.history.push('/ login'),它只會影響最近的<Switch>,因此不會在容器區域中呈現任何內容(因為沒有路由匹配)但保持導航欄可見。 如何從Main.js中獲取父<Switch>來決定在程序化路線更改時呈現什么? 我是否應該以其他方式構建應用程序?

謝謝。

訣竅是在App.js中刪除多余的<Router>,並在文件末尾使用withRouter(App)將其導出。 感謝Nenad Vracar

您可以定義不同的路線集。 默認路線將始終顯示您的導航欄,而其他路線則不會。

class App extends React.Component{
    render(){
        const DefaultRoutes = () => {
            return(
                <div>
                    <Navbar/>
                    <Switch>
                        <Route path="/" component={Landing} exact={true}/>          
                    </Switch>                                                                                                           
                    <Footer/>
                </div>
            )
        }

        return(
            <Provider store={store}>
                <BrowserRouter>
                    <div className="App">
                        <Switch>
                            <Route path="/alternate" component={alternateComponent} exact/>
                            <Route component={DefaultRoutes}/>
                        </Switch>
                    </div>
                </BrowserRouter>
            </Provider>
        )
    }
}

因此,使用此設置,您可以看到DefaultRoutes將始終使用導航欄。 但是,路徑為“備用”的Route則不是這樣。 本質上,只需將要具有“正常”顯示行為的路由包裝在DefaultRoutes中即可。 並定義該集合之外的任何其他路徑。 這要歸功於Switch,它將獨家渲染路線。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM