反应路由器身份验证异步

时间:2017-03-20 17:09:40

标签: javascript reactjs asynchronous react-router

我有新的反应。

我想为我在routes.js中实现的Async-Routes添加一些安全性:

import React from 'react';
import App from './app.jsx';
import Home from './components/home.jsx';

import {Router, Route, IndexRoute, hashHistory} from 'react-router';

function loadRoute(cb) {
  return (module) => cb(null, module.default);
}

const routes = {
    component: App,
    childRoutes: [
        {
            path: "/",
            component: Home
        },
        {
            path: "/hello/:foo",
            getComponent(location, cb) {
                System.import('./components/hello.jsx')
                  .then(loadRoute(cb))
                  .catch(errorLoading);
              }
        },
    ]
};

export default () => <Router history={hashHistory} routes={routes} />

你可以看到&#34; / hello /:foo&#34;路由是异步的。

如何限制对此路线的访问权限(基于角色)并重定向到其他地方(例如登录)?

我只想在需要时加载块。

我应该将检查代码放入&#34; getComponent()&#34;?

可以用&#34; willTransitionTo()&#34;来完成这个功能吗?&#34; getComponent()&#34;我应该如何实施呢?

1 个答案:

答案 0 :(得分:0)

我会将检查代码放入componentWillMount(),并在render()中返回页面组件,或显示/重定向到登录。

如果您有多个需要访问限制的页面,我会为每个页面组件创建一个高级组件顺序,以便在呈现之前检查访问权限。