在一個複雜的SAP應用中,咱們可能須要根據用戶的角色控制用戶進行頁面的權限,甚至在用戶進入系統以前就進行權限的控制。本文就此一權限控制進行討論。本文假設讀者瞭解React和React-Router的相關使用。函數
一個傳統的路由大概長下邊這個樣式,這是沒有添加任何權限限制的。ui
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。spa
假設咱們須要在用戶進入PhotoPage以前須要驗證用戶是否有權限,根據store的的一個狀態去判斷。code
先添加以下一個函數component
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} 屬性get
<Route path="photo" component={PhotoPage} onEnter={authRequired} />
經過以上,就完成了第一個權限的添加權限控制