第十五单元(react路由的封装,以及路由数据的提取)
#课程目标
- 熟悉react路由组件及路由传参,封装路由组件能够处理路由表
- 对多级路由能够实现封装通用路由传递逻辑,实现多级路由的递归传参
- 对复杂的react应用,能够提取路由表并使用路由组件简化路由配置
- 在路由组件中实现路由拦截功能
#知识点
- 封装路由组件
import React from 'react';
import {Switch, Route, Redirect} from 'react-router-dom';
export default (props)=>{
return <Switch>
{
props.routes.map((item, index)=>{
return <Route key={index} path={item.path} render={(props)=>{
if (item.children){
/** 渲染组件,类似于<Tab/>
* ...props 把路由信息展开传递下去
* item.children 把子路由配置传递下去
*/
return <item.component {...props} routes={item.children}/>
}else{
return <item.component {...props}/>
}
}}></Route>
})
}
<Redirect exact from="/" to="/list"></Redirect>
</Switch>
}
- 路由表的配置
// 一级路由
import List from '../components/List';
import Detail from '../components/Detail';
// 二级路由
import Content from '../components/Content';
export default {
routes: [{
path: '/list',
component: List,
children: [{
path: '/list/content',
component: Content
}]
},{
path: '/detail',
component: Detail
}]
}
- 根路由的渲染
// 封装的类似与router-view的组件
import RouterView from './router/RouterView';
// 路由配置
import config from './router/router.co nfig';
ReactDOM.render(<Router>
<RouterView routes={config.routes}></RouterView>
</Router>, document.getElementById('root'));
- 包含子路由的路由渲染
<RouterView routes={this.props.routes}></RouterView>
1
#授课思路
#案例和作业
-
使用封装路由实现抖音主页面的配置及路由传参
-
使用封装路由实现抖音顶部推荐和当前城市的切换