引用:
react-router 還是 react-router-dom?
react-router-dome比react-router多幾個<Link> <BrowserRouter> 這樣的 DOM 類組件。因此我們只需引用 react-router-dom 這個包就行了。當然,如果搭配 redux ,你還需要使用 react-router-redux。
按需加載運行原理:
在router4以前,我們是使用getComponent的的方式來實現按需加載的,router4中,getComponent方法已經被移除,下面引用就介紹了react-router4是如何來實現按需加載的。
[引用](https://segmentfault.com/a/1190000009539836)
一、如果想要使用默認路由
1.需要使用<Switch>標簽將需要默認選擇的標簽層級包起來
2.在<Switch>元素的最后使用<Redirect>標簽;否則會報warning:
Warning: You tried to redirect to the same route you're currently on: "/home"
二、如果需要在App 組件中使用{ this.props.children }
1.則需要在頁面中使用<Switch>元素中嵌套App 中的子組件
<Route><Home ></Home></Route>
<Route><Help ></Home></Route>等;
三、react-router(v4.2.0)版本中沒有對象hashHistory;但是有幾個特定標簽(BrowserRouter、HashRouter、MemoryRouter這三種Router) ;如果也可以單獨引入history來創建。
1)npm install history --save;
import {createBrowserHistory} from 'history';
const hashHistory = createBrowserHistory();
2)<HashRouter></HashRouter>
注意:
1)createHashHistory來創建hashHistory;點擊同一個相同的路由會報warning;
Warning: Hash history cannot PUSH the same path; a new entry will not be added to the history stack
需要將createHashHistory改成createBrowserHistory則不會報warning
2)但是使用createBrowserHistory,刷新頁面會報錯;找不到路徑。最好是使用<HashRouter></HashRouter>
完整栗子:
import './index.less'
import React from 'react';
import ReactDOM from 'react-dom';
import {Router, Route, Switch, Redirect,HashRouter} from 'react-router-dom';
import App from './container/app'
import Home from './container/Home'
import A from './container/Help/A'
import B from './container/Help/B'
import C from './container/Help/C'
import Help from './container/Help'
let rootElement = document.getElementById('root');
ReactDOM.render(
<HashRouter>
<Route path="/" render={({history, location}) => (
<App history={history} location={location}>
{/*Switch只渲染出第一個與當前訪問地址匹配的 <Route> 或 <Redirect>。*/}
<Switch>
<Route path="/home" component={Home}/>
<Route path="/login" render={(({location}) => (<h1>login</h1>))}/>
<Route path="/help" render={({history, location, match}) => (
<Help history={history} location={location} match={location}>
<Switch>
<Route path="/help/a" exact component={A}/>
<Route path="/help/b" component={B}/>
<Route path="/help/c" component={C}/>
<Redirect to={{pathname: '/help/a'}}/>
</Switch>
</Help>
)}/>
<Redirect to={{pathname: '/home'}}/>
</Switch>
</App>
)}/>
</HashRouter>
, rootElement
);