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

问题描述 投票:3回答:2

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

我有一个休息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);

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

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

UPDATE

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

reactjs redux react-router react-redux react-router-redux
2个回答
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} />
  );
}

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


2
投票

您可以在Route上使用onEnter prop for conditional auth。 您可以检查用户是否有权进入视图,如果用户没有,则将其导航到其他位置。

请参阅: 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: '/'});
  }
}  

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

© www.soinside.com 2019 - 2024. All rights reserved.