【问题标题】:User role based routes基于用户角色的路由
【发布时间】:2019-12-19 06:46:25
【问题描述】:

我正在为我的前端使用 react

我正在登录,忘记了路由中的密码

根据用户类型,我需要包含几组路线

前

  • 用户类型

    Student:
        Dashboard, Profile, View Attendance 
    Teacher :
        Dashboard, Profile, add Attendance, Student Profile 
    

登录后只有我知道用户类型。

如果我在渲染应用程序组件时加载所有路由,则会加载不需要的路由。

因此学生可以使用教师组件。这可能会导致问题。

如何解决这个问题

【问题讨论】:

    标签: reactjs routes react-router


    【解决方案1】:

    您可以使用react-authorization 将组件包装在路由中,并只允许特定角色的用户查看它。您还可以定义将向未经授权的用户显示的错误组件。这是一个示例(在 TypeScript 中):

    const AdministrationRoute: React.FC<AdministrationRouteProps> = props => {
        const accessDeniedError = <div className="ml-3 mr-3"><Alert
            color="danger">Access denied!</Alert></div>;
        return <IfGranted expected="ROLE_ADMIN" actual={props.user.roles} unauthorized={accessDeniedError}>
            <Users/>
        </IfGranted>;
    };
    

    然后像往常一样在路由中使用组件:

    <Route path={Routes.administration.path} component={AdministrationRoute}/>
    

    免责声明:我是 react-authorization 库的作者。

    【讨论】:

      猜你喜欢
      • 2021-09-20
      • 2015-01-30
      • 1970-01-01
      • 1970-01-01
      • 2016-06-12
      • 2012-01-01
      • 1970-01-01
      • 2018-09-08
      • 2015-07-17
      相关资源
      最近更新 更多