React-Router v4
一. Switch 、Router 、Route三者的区分
1、Route
Route 是竖立location 和 ui的最直接联络
2、Router
react-router v4 中,Router被拆分成了StaticRouter、MemoryRouter、BrowserRouter、HashRouter、NativeRouter。
MemoryRouter、BrowserRouter、HashRouter 即是
import { Router } from 'react-router'
<!--这里能够有三种-->
<!--history 部份源码
exports.createBrowserHistory = _createBrowserHistory3.default;
exports.createHashHistory = _createHashHistory3.default;
exports.createMemoryHistory = _createMemoryHistory3.default;
-->
import createBrowserHistory from 'history/createBrowserHistory'
//
const history = createBrowserHistory()
<Router history={history}>
<App/>
</Router>
NativeRouter(给rn运用的)
A <Router> for iOS and Android apps built using React Native.
这里新增strict 和 exact
运用了strict location 大于即是path才婚配,eq path=’/one’ location=’/one/a’能婚配。
运用了exact location 约即是 path 才婚配,eq path=’/one’ location=’/one’或许 ‘/one/’能婚配,所以说是约即是。
运用了exact 和 strict location = path才婚配
StaticRouter(后续补充)
3、Switch
这是v4版本中新增加,重要用来做唯一婚配的功用。就是想要在浩瀚路由中只婚配个中一个路由。
二、v4 版本中路由应当怎样设置呢?
1.基础设置(这个和v3中基础一致,结果也基础一样)
婚配 <= location eq.( /b => / + /b ) ( / => / )
<BrowserRouter forceRefresh={!supportsHistory} keyLength={12}>
<div>
<Route path="/" component={aContainer} />
<Route path="/b" component={bContainer} />
</div>
</BrowserRouter>
2.含Switch 设置
婚配 <= location eq.( /b => /b ) ( / => / ) 唯一婚配
<BrowserRouter forceRefresh={!supportsHistory} keyLength={12}>
<Switch>
//这里用exact,仅仅是忧郁location被 path='/'截胡了。
<Route exact path="/" component={aContainer} />
<Route path="/b" component={bContainer} />
</Switch>
</BrowserRouter>
题目(三个题目)
1.怎样设置大众的Component
第一种体式格局
<BrowserRouter forceRefresh={!supportsHistory} keyLength={12}>
<div>
<Route path="/" component={aContainer} />
<Route path="/b" component={bContainer} />
</div>
</BrowserRouter>
第二种体式格局(父子嵌套)
<BrowserRouter forceRefresh={!supportsHistory} keyLength={12}>
<div >
<Route path="/" component={aContainer} />
<Route path="/b" component={Parent} />
{/* {app()} */}
</div>
</BrowserRouter>
const Parent = ({ match }) => (
<div>
<Route path={`${match.url}/`} component={bContainer} />
<Route path={`${match.url}/c`} component={cContainer} />
<Route path={`${match.url}/d`} component={dContainer} />
</div>
);
这类状况 bContainer就是是公用的Component
2.怎样设置getComponent,按需加载
3.是不是有简化写法
npm install --save react-router-config
第一步 设置路由
const routes = [
{ component: bContainer,
routes: [
{ path: '/',
exact: true,
component: bContainer
},
{ path: '/b/b',
component: bContainer,
routes: [
{ path: '/b/b/b',
component: bContainer
}
]
}
]
}
]
第二步 设置路由
<BrowserRouter forceRefresh={!supportsHistory} keyLength={12}>
<div >
{renderRoutes(routes)}
</div>
</BrowserRouter>
第三步 需要在container的render中去挪用要领
<div>
1111
{renderRoutes(this.props.route.routes)}
</div>
这个上风是能够一致设置,劣势是需要在container中一致挪用,然则这个抽出来一致完成,题目也不大,而且还能够处理 题目一。
这个renderRoutes现实是就是用一层Switch和多个Route来包了一层。