react 嵌套路由

二级路由必须用/home/news (父级路由+新路由)
有二级路由的一级路由不能开启严格模式

二级路由

import React, { Component } from 'react'
import { Route,Switch} from 'react-router-dom'
import MyNavLink from '../../components/MyNavLink'
import Message from './Message'
import News from './News'
export default class ABCD extends Component {
  render() {
    return (
    <div>
        <h2>Home组件内容</h2>
        <div>
          <ul className="nav nav-tabs">
            <li>
              <MyNavLink to='/home/news'> News</MyNavLink>
            </li>
            <li>
              <MyNavLink to='/home/message'>Message</MyNavLink>
            </li>
          </ul>
          <Switch>
            {/* 注册路由 */}
            <Route path="/home/news" component={News}/>
            <Route path="/home/message" component={Message}/>
          </Switch>
        </div>
      </div>
    )
  }
}


一级路由

import React, { Component } from 'react'
import { Route,Switch,Redirect } from 'react-router-dom'
import ABCD from './pages/Home'
import About from './pages/About'
import Header from './components/Hearder'
import MyNavLink from './components/MyNavLink'

export default class App extends Component {
  render() {
    return (
      <div>
        <div className="row">
          <div className="col-xs-offset-2 col-xs-8">
            <Header/>
          </div>
        </div>
        <div className="row">
          <div className="col-xs-2 col-xs-offset-2">
            <div className="list-group">
              {/* 原生html中,靠<a>跳转不同的页面 */}
              {/* <a className="list-group-item" href="./about.html">About</a>
              <a className="list-group-item active" href="./home.html">Home</a> */}
              
              {/* 在React中靠路由链接实现切换组件 编写路径连接 */}
              <MyNavLink to="/about">About</MyNavLink>
              <MyNavLink to="/home">Home</MyNavLink>
            </div>
          </div>
          <div className="col-xs-6">
            <div className="panel">
              <div className="panel-body">
                {/* Switch 使用后 只要匹配到对应的路由,就直接跳出去 不再往下接着判断 */}
                <Switch>
                  {/* 注册路由 */}
                  <Route path="/about" component={About} />
                  <Route path="/home" component={ABCD} />
                  <Redirect to="/home" />
                </Switch>
              </div>
            </div>
          </div>
          </div>
      </div>
    )
  }
}

总结

  1. 注册子路由时要写上父路由的path值
  2. 路由的匹配是按照注册路由的顺序进行的
上一篇:Unit2 Talking about your hopes and dreams


下一篇:Python 全栈系列110 -elasticsearch 从安装到hello