【问题标题】:React-router nested routes with history.push使用 history.push 的 React-router 嵌套路由
【发布时间】:2019-05-30 21:24:31
【问题描述】:

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

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') 它只会影响最近的 因此不渲染容器区域中的任何内容(因为没有匹配的路线),但保持导航栏可见。如何从 Main.js 获取父 来决定在程序化路由更改时呈现什么?我应该以其他方式构建应用程序吗?

谢谢。

【问题讨论】:

  • 这在这里什么也做不了。 withRouter 为使用 Route 组件的 component 属性时已经存在的组件添加功能。
  • 我想我在这里犯了一个错误。尝试删除 App 上的路由器包装器并改用 withRouter
  • 这完全符合我的要求。因此,如果我理解正确,我正在创建另一个我在这里不需要的路由器。谢谢!我会据此创建一个答案并感谢您。
  • 我昨天也遇到了同样的问题,这篇文章帮了我github.com/ReactTraining/react-router/blob/master/packages/…
  • 为链接干杯!

标签: javascript reactjs react-router


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    您可以定义不同的路线集。将始终显示您的导航栏的默认路线,以及不会显示的其他路线。

    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,它将专门渲染路线。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-11-04
      • 1970-01-01
      • 1970-01-01
      • 2015-02-21
      • 2017-02-03
      • 2017-08-28
      • 1970-01-01
      相关资源
      最近更新 更多