React-Router-在运行时添加/删除路由

时间:2017-01-17 09:15:16

标签: reactjs redux react-router react-redux react-router-redux

我有一个支持每个用户权限的应用程序。因此,如果用户必须具有适当的权限,他就能够管理用户,组等。如果用户没有这样的许可,他可能不会这样做。

我有一个休息api,有一个端点,返回当前用户的所有允许链接,有了这个,我想设置react-router的路由。如果编辑了权限,并且例如用户失去了编辑用户的权限,则相应的菜单项应该从菜单中消失并且路由从路由器中删除。否则,应添加菜单项和路线。

现在我有了这个设置:

ReactDOM.render(
  <Provider store={store}>
    <Router history={history}>
      <Route path="/" component={Window}>
        <IndexRoute component={Users} />
        <Route path="users" component={Users} />
        <Route path="groups" component={Groups} />
        <Route path="permissions" component={Permissions} />
        <Route path="*" component={Error} />
      </Route>
    </Router>
  </Provider>, mount);

但我真的想拥有:一个动态执行此设置的功能,每次权限更改时都可以运行。

我找不到任何关于这方面的文件,如果有办法,我会很高兴。

更新

根据给出的答案和评论,我意识到我想解决这个问题的方式并不符合react-router的声明性质。

2 个答案:

答案 0 :(得分:4)

在我的一个项目中,我有以下设置,我认为你会发现它很有用:

componentWillMount() {
  let routes = [];

  routes.push({
    path: '/authenticate',
    component: LoginPage
  });

routes.push({
  path: '/',
  component: Main,
  indexRoute: { component: null },
  getChildRoutes: (error, callback) => {
    getNavigation().then((nav) =>{
      callback(null, getChildRoutes(nav.paths))
    })
  },
  onEnter: () => {
    getNavigation();
    let token = getToken();
    if (token == null || token === '') redirectToAuthenticationUrl();
  }
});

this.routes = routes;

render() {
  return (
    <Router key={uuid()} history={history} routes={this.routes} />
  );
}

您可以将路线存储在对象中,并传递将返回路线的承诺,您也可以通过这种方式轻松检查权限。希望有所帮助!

答案 1 :(得分:2)

您可以使用onEnter Route道具作为条件身份验证。您可以检查用户是否有权进入该视图,如果他们没有,则将其导航到其他地方。

请参阅:https://github.com/ReactTraining/react-router/blob/master/docs/API.md#onenternextstate-replace-callback

<Route path='/accounts' component={Accounts} onEnter={isAuth} />

const isAuth = (nextState, replace) => {
  if (!isCurrentUserAuthorised) {
    replace({pathname: '/'});
  }
}  

导航到isAuth时输入/accounts方法。显然,您需要将自己的逻辑用于确定用户是否获得授权,但这是其中的要点。只需输入您希望将未经授权的用户送到的路径名。

相关问题