本篇文章主要介绍了react-router如何进行页面权限管理的方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
前言
在一个复杂的sap应用中,我们可能需要根据用户的角色控制用户进行页面的权限,甚至在用户进入系统之前就进行权限的控制。本文就此一权限控制进行讨论。本文假设读者了解react和react-router的相关使用。
从传统的router开始
一个传统的路由大概长下边这个样式,这是没有添加任何权限限制的。
export default (store) => { const history = synchistorywithstore(hashhistory, store); return ( <router history={history}> <route path="/" component={approot} > <indexroute component={indexpage} /> <route path="photo" component={photopage} /> <route path="info" component={infopage} /> </route> {/* <redirect path="*" to="/error" /> */} </router> )}
这里一共有3个页面 indexpage, photopage,infopage。
添加第一个权限
假设我们需要在用户进入photopage之前需要验证用户是否有权限,根据store的的一个状态去判断。
先添加如下一个函数
const authrequired = (nextstate, replace) => { // now you can access the store object here. const state = store.getstate(); if (state.admin != 1) { replace('/'); } };
函数里我们判断了state的admin是否等于1,否则跳转到首页。
然后在route添加 onenter={authrequired} 属性
<route path="photo" component={photopage} onenter={authrequired} />
通过以上,就完成了第一个权限的添加
进入系统之前就进行权限控制
如果需要在进入系统之前就进行权限控制,那么就需要改变一下策略。
比如上边的例子,加入state的admin并未加载,那么就需要在上一层的route进行数据加载
首先添加一个加载数据的函数
function loaddata(nextstate, replace, callback) { let unsubscribe; function onstatechanged() { const state = store.getstate(); if (state.admin) { unsubscribe(); callback(); } } unsubscribe = store.subscribe(onstatechanged); store.dispatch(actions.queryadmin()); }
接着再修改一下router
<router history={history}> <route path="/" component={approot} onenter={loaddata}> <indexroute component={indexpage} /> <route path="photo" component={photopage} onenter={authrequired} /> <route path="info" component={infopage} /> </route> </router>
这样在进入下边之前,就会先进行数据加载。
通过以上简单几步,一个完整的权限控制链就完成了.
上面是我整理给大家的,希望今后会对大家有帮助。
相关文章:
在angularjs中如何实现猜数字大小功能
在jquery中图片查看插件如何使用
在vue中如何实现分页组件
使用vue实现简单键盘操作
在react中详细介绍受控组件与非受控组件
以上就是在react-router中如何进行页面权限管理的详细内容。