React-router 使用 History.push 嵌套路由

use*_*476 3 javascript reactjs react-router

我有一个反应页面,它根据当前路由呈现登录页面或导航栏+容器组件。我不希望导航栏在登录页面中可见。我的应用程序的结构如下:

索引.js

ReactDOM.render(<Main/>, document.getElementById('root'));
Run Code Online (Sandbox Code Playgroud)

Main.js

<Router>
  <Switch>
    <Route path="/login" component={Login} />
    <PrivateRoute path="/" component={App} />
  </Switch>
</Router>
Run Code Online (Sandbox Code Playgroud)

应用程序.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>
Run Code Online (Sandbox Code Playgroud)

现在,如果在任何容器组件内部我想做一个 this.props.history.push('/login') 它只会影响最近的 < Switch > ,因此不会在容器区域中渲染任何内容(因为没有路由匹配)但保持导航栏可见。我如何从 Main.js 获取父级 < Switch > 来决定在编程路由更改时渲染什么?我应该以其他方式构建应用程序吗?

谢谢。

use*_*476 5

诀窍是删除 App.js 中多余的 < Router > 并在文件末尾使用 withRouter(App) 将其导出。谢谢内纳德·弗拉卡尔