一、修改路由
config/router.config.js
{
authority: ['管理员','教师'],
// path: '/CourseManagement/course',
path: '/CourseManagement/CourseEditType',
name: '课程',
icon: 'home',
component: './CourseManagement/index',
},
{
authority: ['管理员','教师'],
name: '班级',
// path: '/CourseManagement/class',
path: '/CourseManagement/CourseNoneEditType',
component: './CourseManagement/index',
icon: 'setting',
},
二、改为订阅
原本在该页面的index.js的componentDidMount()中切分保存路由中两个页面的标识,后改在dva中处理
修改前:
componentDidMount() {
const path = window.location.pathname;
console.log(path);
const reg = /\/CourseManagement\/(\w+)/;
const Result = reg.exec(path);
const routerType = Result[1];
console.log(routerType);
this.setState({routerType});// 存在当前页面的state中
}
修改后:
subscriptions: {
setupHistory({dispatch, history}) {
history.listen((location) => {
const {pathname} = location;
const reg = /\/CourseManagement\/(\w+)/;
if (reg.test(pathname)) {
const courseState = reg.exec(pathname)[1];
console.log(courseState)
dispatch({ // 存在dva的state中
type: 'save',
payload: {
courseState,
},
})
}
})
}
},
三、总结
共用页面优点:
-
代码复用: 通过共用一个页面,可以避免重复编写相似的代码。这样可以减少开发工作量,并且在维护时也更加方便,因为只需修改一个页面即可。
-
统一风格和布局: 共用一个页面可以确保这两个页面具有统一的风格和布局,从而提升用户体验。用户在不同页面间切换时,不会感受到突兀或不一致的界面变化。
-
性能优化: 使用路由切换页面可以避免每次切换都重新加载整个页面的内容。这可以提高页面加载速度,因为只需加载页面中变化的部分,而不是整个页面。
将路由处理移到 dva 中的优点:
-
分离关注点: 将路由处理移到 dva 中可以更好地分离关注点。在原本的实现中,组件的生命周期方法中包含了与路由相关的逻辑,这违反了单一责任原则。通过将路由处理移到 dva 中,可以使组件更专注于自身的业务逻辑,而将路由相关的逻辑交给 dva 处理。
-
方便访问和共享: 将路由信息存储在 dva 的状态中,可以方便地在整个应用程序中访问和共享这些信息。其他组件或模块可以通过订阅 dva 的状态来获取当前路由信息,而不需要依赖于特定的组件实现。
-
测试和调试: 将路由处理移到 dva 中可以更方便地进行测试和调试。因为路由相关的逻辑现在是在 dva 中处理的,所以可以单独对 dva 模块进行测试,并且可以更容易地模拟不同的路由情况进行测试。