引用:
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
);