前言
在一個復雜的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>這樣在進入下邊之前,就會先進行數據加載。
通過以上簡單幾步,一個完整的權限控制鏈就完成了.
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答