React-router v4 路由配置方法小结

React-router v4 路由配置方法小结

本文主要介绍了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()} *

tag:方法路由配置电脑软件Reactrouter

相关内容