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>

这样在进入下边之前,就会先进行数据加载。
通过以上简单几步,一个完整的权限控制链就完成了.

猜你喜欢

转载自blog.csdn.net/qq_39985511/article/details/80885158