React Router被拆分成三个包:react-router,react-router-dom和react-router-native。react-router提供核心的路由组件与函数。其余两个则提供运行环境(即浏览器与react-native)所需的特定组件。

进行网站(将会运行在浏览器环境中)构建,我们应当安装react-router-dom。react-router-dom暴露出react-router中暴露的对象与方法,因此你只需要安装并引用react-router-dom即可。

src/router.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import React from 'react'
import { Switch, Route, Redirect, routerRedux } from 'dva/router'
import dynamic from 'dva/dynamic'
import App from './routes/App'
const { ConnectedRouter } = routerRedux
const Routers = function ({ history, app }) {
const error = dynamic({
app,
component: () => import('./routes/error'),
})
const routes = [
{
path: '/dashboard',
models: () => [import('./models/dashboard')],
component: () => import('./routes/dashboard/'),
}
]
return (
<ConnectedRouter history={history}>
<App>
<Switch>
<Route exact path="/" render={() => (<Redirect to="/dashboard" />)} />
{
routes.map(({ path, ...dynamics }, key) => (
<Route key={key}
exact
path={path}
component={dynamic({
app,
...dynamics,
})}
/>
))
}
<Route component={error} />
</Switch>
</App>
</ConnectedRouter>
)
}
export default Routers
  • App为所有页面都需要加载的组件,既外部框架
  • dva/dynamic: 解决组件动态加载问题的 util 方法,基于 react-async-component 实现。
  • 参考文章

src/routes/app.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import { connect } from 'dva'
import { withRouter } from 'dva/router'
const App = ({
child
}) => {
return (
<div>
<Header>
{child}
</div>
)
}
export default withRouter(connect(({ app, loading }) => ({ app, loading }))(App))
  • 组件传入withRouter()中,使组件带有child属性
  • child为路由匹配到的组件