如何用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>
這樣在進入下邊之前,就會先進行數據加載。
通過以上簡單幾步,一個完整的權限控製鏈就完成了.
最後更新:2017-11-16 22:04:06