简体   繁体   English

如何在React应用中处理权限检查(在Redux中进行状态维护)?

[英]How to handle permission check in React app (State maintain in Redux)?

How to handle permission check in React? 如何在React中处理权限检查? I tried in two ways. 我尝试了两种方式。 Any better way to handle permission check or which one is most good to use? 还有什么更好的方法来处理权限检查,或者哪种方法最合适?

Type 1 类型1
Pass permissions via context. 通过上下文传递权限。 Permission component gets permissions from context if permission satisfy return component or null 如果权限满足返回组件,则权限组件从上下文获取权限;或者返回null

class HomePage extends React.Component{
  getChildContext(){
   return {permission:this.props.permission}
  }
   render(){
     return <div>
       <Permission check='Edit'>
         <PopupMenu> 
           <div>Edit</div>
         </PopupMenu>
       </Permission>
       <Permission check='Delete'>
         <PopupMenu> 
            <div>Delete</div>
         </PopupMenu>
       </Permission>
   </div>
  }
}
HomePage.childContextType={permission:...}
class Permission extends React.Component{
    render(){
       if(this.context.permissions.indexOf(this.props.check)!=-1)
         return this.props.children
       else
         return null;
    }
}

Type 2 2型
Check the permission in the mapStateToProps function and return props based on permission 在mapStateToProps函数中检查权限,并根据权限返回道具

class HomePage extends React.Component{
    render(){
    return <div>
       <PopupMenu> 
          <div>{this.props.operation}</div>
       </PopupMenu>
    </div>
    }
  }
function mapStateToProps(state){
   var operation="";
   if(state.permission=="Edit"){
      operation="Edit"
   }
   else if(state.permission=="Delete"){
      operation="Delete"
   }
   return {operation}
}
connect(mapStateToProps)(HomePage)

either solution is fine. 两种解决方案都可以。 Note the 2nd solution offers various levels of access, while the first solution is "all or nothing". 请注意,第二种解决方案提供各种访问级别,而第一种解决方案是“全部或全部”。 So it just depends upon your needs and coding style preferences. 因此,这仅取决于您的需求和编码样式首选项。

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

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