简体   繁体   English

反应应用程序和用户角色

[英]React Application and User Roles

Is there a "built in" way to scope with different user roles in React Application? 在React Application中是否有一种“内置”方式可以使用不同的用户角色? I want certain tabs, menus and links (routes) to be available only for certain users and not for others. 我希望某些标签,菜单和链接(路线)仅适用于某些用户,而不适用于其他用户。 Also the content and options of many views will vary depending on the role. 此外,许多视图的内容和选项将根据角色而有所不同。 I know how to manage roles in the back end and retrieve them during the authentication in the JWT token, but what is the best way to parametrize the client side state and representation based on the roles? 我知道如何在后端管理角色并在JWT令牌中进行身份验证时检索它们,但是根据角色参数化客户端状态和表示的最佳方法是什么? Is the Redux and render logic conditions way to go, or is there more streamlined solution, which necessarily doesn't demand the client browser to know all possible states for different roles prior to authentication? Redux和呈现逻辑条件是否可行,或者是否有更简化的解决方案,这必然不要求客户端浏览器在身份验证之前知道不同角色的所有可能状态?

I can suggest write a higher order component which takes roles who can see the feature. 我可以建议编写一个更高阶的组件,它可以扮演可以看到该功能的角色。

const AuthorizeOnly = ({ children, allowedRoles, user }) => (
  allowedRoles.includes(user.role)
  && (
  <React.Fragment>
    {children}
  </React.Fragment>
  )
);

// some component //某个组件

loggedInUser = {
  name:'john',
  role:'admin' 
}
render(){
   <div>
     <AuthorizedOnly allowedRoles={['admin']} user={loggedInUser}>
       <p>only admin can see this.</p>
      </AuthorizedOnly>
   </div>
 }

You can tweak the logic inside AuthorizedOnly component based on your business logic. 您可以根据业务逻辑调整AuthorizedOnly组件中的逻辑。

For Router you can use the similar component which returns a Route based on your condition 对于路由器,您可以使用类似的组件,该组件根据您的条件返回Route

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM