2017-07-15 192 views
0
import React, { Component } from 'react'; 
import {BrowserRouter as Router,Route,Switch} from 'react-router-dom'; 
import Home from './home/components/home' 

class App extends Component { 
render() { 
return (
    <div className="App"> 

     <Router> 
     <Switch> 
     <Route path="/home" component={Home}> 
     </Route><!--working--> 

     <!--<Route path="/" component={Home}> 
     </Route> not working --> 

     </Switch> 
     </Router> 

    </div> 
); 
} 
}  


class Home extends Component{  
    render =() => { 

    return (
     <div> 
      <div>Home</div> 
      <Route exact path={`${this.props.match.url}/signin`} component={SignIn}> 
      </Route> 
     </div> 

    ); 
} 
} 

我有以下一段代碼。在App組件中,我想創建嵌套的路線。 '/'是根路由,/ signin是嵌套路由。不過/ signin不會呈現SignIn組件,只是'Home'div。當我在App組件中用'/'替換'/'時,'/ home/signin'會呈現'Home'div和'SignIn'組件。我在這裏做錯了什麼?React路由器4個嵌套路由沒有得到渲染

回答

1

嵌套路由不能在根上工作。只需使用充當父級組件的佈局組件即可獲得相同的結果。一旦你點擊一個鏈接,子組件將在佈局組件中的指定區域內呈現。我創建了一個例子你就CodePen:https://codepen.io/anon/pen/EXMJzG

const { 
 
    BrowserRouter, 
 
    Link, 
 
    Route 
 
} = ReactRouterDOM; 
 
const Router = BrowserRouter; 
 

 
// App 
 
class App extends React.Component{ 
 
    render(){ 
 
    return(
 
    <Router> 
 
     <div className="container"> 
 
     <Layout> 
 
      <Route exact path="/" component={Home} /> 
 
      <Route exact path="/signin" component={SignIn} /> 
 
      <Route exact path="/cake" component={Cake} /> 
 
     </Layout> 
 
     </div> 
 
    </Router> 
 
    ) 
 
    } 
 
} 
 

 
//Layout 
 
const Layout = ({children}) => (
 
    <div> 
 
    <header> 
 
     <h1>Header</h1> 
 
    </header> 
 
    <nav> 
 
     <Link to="/">Home</Link> 
 
     <Link to="/signin">Sign In</Link> 
 
     <Link to="/cake">Cake</Link> 
 
    </nav> 
 
    <section> 
 
     {children} 
 
    </section> 
 
    <footer> 
 
     <p>Footer</p> 
 
    </footer> 
 
    </div> 
 
) 
 

 
//Home 
 
const Home =()=>(
 
    <div> 
 
    <h1>Hello World</h1> 
 
    </div> 
 
) 
 

 
//SignIn 
 
const SignIn =()=>(
 
    <div> 
 
    <h1>Sign In</h1> 
 
    </div> 
 
) 
 

 
//Cake 
 
const Cake =()=>(
 
    <div> 
 
    <h1>Free Cake</h1> 
 
    </div> 
 
) 
 

 
ReactDOM.render(<App />,document.getElementById('app'));