React Router有子路由使用IndexRoute設定首頁

12 月 18, 2018 | | 0 條留言

IndexRoute

在我們的應用中,如果訪問/ ,只會顯示一個空白頁。而我們的理想情況是先一個Home頁,所以我們先建立一個Home組件,再去講接下來怎麼做。新建文件modules/Home.js並添加代碼:

// modules/Home.js
import React from 'react'

export default React.createClass({
  render() {
    return <div>~~男神女神~~</div>
  }
})

一種方式是,先看App裡面有子路由激活嗎?如果沒有,你們顯示Home。這種方式,App.js的代碼為:

// App.js
import Home from './Home'
// ...
<div>
  {/* ... */}
  {this.props.children || <home></home>}
</div>
//...

這種方式也可以正常工作,但是我們更希望Home像Boys和Girls那樣,綁定到一個路由上。這才更符合React Router的思想,一個組件綁定到一個路由上,通過路由的嵌套、激活等顯示不同的界面。這種方式的實現要用到IndexRoute組件。只需改變index.js中的代碼:

//...
import { Router, Route, hashHistory, IndexRoute } from 'react-router'
import Home from './modules/Home'
// ...
render((
  <router history="{hashHistory}">
    <route component="{App}" path="/">
      <indexroute component="{Home}/">
      <route component="{Boys}" path="/boys">
          <route component="{Boy}/" path="/boys/:boyName">
      </route>
      <route component="{Girls}/" path="/girls">
    </route>
  </route></indexroute></route></router>
), document.getElementById('app'))

上面代碼的第2行,新引入了IndexRoute組件,第3行導入Home組件。在App路由中,加入了。打包運行,點擊右側的"訪問測試"看下效果,進入網頁後直接看到Home組件。

注意,IndexRoute組件沒有path屬性。IndexRoute只有當其父路由的所有其他子路由(IndexRoute的所有兄弟路由)都沒有激活時,才是父路由的this.props.children,並顯示出來。如果Boys路由激活了,那麼Boys組件才是App的this.props.children,並顯示出來。