Nested Routes in React Router v4

前端 未结 5 1294
梦毁少年i
梦毁少年i 2020-11-29 22:02

I\'m trying to set up some nested routes to add a common layout. Check the code out:

  
    
      
相关标签:
5条回答
  • 2020-11-29 22:39

    You can also try this :

    <Route exact path="/Home"
                     render={props=>(
                                     <div>
                                          <Layout/>
                                          <Archive/>
                                    </div>
                           )} 
        />
    
    0 讨论(0)
  • 2020-11-29 22:42

    If you do not want Layout to run at loaded. Use this method:

    <div className="container">
        <Route path="/main" component={ChatList}/>
        <Switch>
            <Route exact path="/" component={Start} />
            <Route path="/main/single" component={SingleChat} />
            <Route path="/main/group" component={GroupChat} />
            <Route path="/login" component={Login} />
        </Switch>
    </div>
    

    Whenever history changes, componentWillReceiveProps in the ChatList will run.

    0 讨论(0)
  • 2020-11-29 22:47

    CESCO's answer renders first the component AppShell then one of the components inside Switch. But these components are NOT going to render inside AppShell, they will NOT be children of AppShell.

    In v4 to wrap components you don't put anymore your Routes inside another Route, you put your Routes directly inside a component.
    I.E : for the wrapper instead of <Route component={Layout}> you directly use <Layout>.

    Full code :

      <Router>
        <Layout>
          <Route path='/abc' component={ABC} />
          <Route path='/xyz' component={XYZ} />
        </Layout>
      </Router>
    

    The change is probably explained by the idea to make React Router v4 to be pure React so you only use React elements like with any other React element.

    EDIT : I removed the Switch component as it's not useful here. See when it's useful here.

    0 讨论(0)
  • 2020-11-29 22:48

    Try:

    <Router>
        <Layout>
            <Route path='/abc' component={ABC} />
            <Route path='/xyz' component={XYZ} />
        </Layout>
    </Router>
    
    0 讨论(0)
  • 2020-11-29 22:49

    You need to use the switch component to nesting to work nice. Also, see this question

    // main app
    <div>
        // not setting a path prop, makes this always render
        <Route component={AppShell}/>
        <Switch>
            <Route exact path="/" component={Login}/>
            <Route path="/dashboard" component={AsyncDashboard(userAgent)}/>
            <Route component={NoMatch}/>
        </Switch>
    </div>
    

    And version-4 components do not take children, instead, you should use the render prop.

    <Router>
        <Route render={(props)=>{
          return <div>Whatever</div>}>
        </Route>
      </Router>
    
    0 讨论(0)
提交回复
热议问题