React Router 4嵌套路由未呈现

时间:2017-07-15 13:20:39

标签: reactjs react-router

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组件中,我想创建嵌套路由。 &#39; /&#39;作为根路由和/ signin是嵌套路由。但是/ signin不会渲染SignIn组件,只是#&#39; Home&#39; DIV。当我更换&#39; /&#39;与&#39; / home&#39;在App组件然后&#39; / home / signin&#39;呈现&#39; Home&#39; div和&#39; SignIn&#39;零件。我在这里做错了什么?

1 个答案:

答案 0 :(得分:1)

嵌套路由在root上不起作用。只需使用充当父组件的布局组件即可获得相同的结果。单击链接后,子组件将在布局组件的指定区域内呈现。我在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'));