如何在 react redux 应用程序中实现基于角色的限制/权限? [英] How to implement Role based restrictions/permissions in react redux app?
问题描述
我有一个包含多个组件的 React-Redux-KoaJs 应用程序.我的用户角色也很少.现在我想只向特定角色显示几个按钮、表格和 div,而对其他人隐藏它们.请记住,我不想隐藏整个组件,而只是隐藏组件的一部分.谁能帮我?提前致谢.
您可以按照@Eudald Arranz 的建议检查每个组件中的角色或权限.或者您可以编写一个组件来检查您的权限.例如:
从'prop-types'导入PropTypes;从'react-redux'导入{连接};const ShowForPermissionComponent = (props) =>{const couldShow = props.userPermissions.includes(props.permission);返回 canShow ?props.children : null;};ShowForPermissionComponent.propTypes = {权限:PropTypes.string.isRequired,用户权限:PropTypes.array.isRequired};const mapStateToProps = state =>({userPermissions: state.user.permission//<--- 在这里你将从 Redux 商店获得你的用户的权限});export const ShowForPermission = connect(mapStateToProps)(ShowForPermissionComponent);
然后你可以像这样使用这个组件:
从'react'导入React;从 './ShowForPermission' 导入 { ShowForPermission };缺点 MyComponent = props =>{返回 (<div><ShowForPermission permission="DELETE"><按钮>删除</按钮></ShowForPermission>
);}
I have a React-Redux-KoaJs application with multiple components. I have few user roles as well. Now i want to display few buttons, tables and div to only specific roles and hide those from others. Please remember i dont want to hide the whole component, but just a part of the components. Can anyone help me? Thanks in advance.
You can check the role or permission in every component as @Eudald Arranz proposed. Or you can write a component that will checks permissions for you. For example:
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
const ShowForPermissionComponent = (props) => {
const couldShow = props.userPermissions.includes(props.permission);
return couldShow ? props.children : null;
};
ShowForPermissionComponent.propTypes = {
permission: PropTypes.string.isRequired,
userPermissions: PropTypes.array.isRequired
};
const mapStateToProps = state => ({
userPermissions: state.user.permission //<--- here you will get permissions for your user from Redux store
});
export const ShowForPermission = connect(mapStateToProps)(ShowForPermissionComponent);
and then you can use this component like this:
import React from 'react';
import { ShowForPermission } from './ShowForPermission';
cons MyComponent = props => {
return (
<div>
<ShowForPermission permission="DELETE">
<button>Delete</button>
</ShowForPermission>
</div>
);
}
这篇关于如何在 react redux 应用程序中实现基于角色的限制/权限?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!