Ant Design Pro 使用Authorized组件作权限验证

Ant Design Pro作为阿里旗下的开源前端框架其优秀和优点就不用赘述了。
请看下图

今天咱们要讲的是如何在ant design pro中作权限验证。

先上代码:javascript

import RenderAuthorized from '../components/Authorized';

const user=getUser();
const Authorized = RenderAuthorized(user.role);
const noMatch = <Alert message="No permission." type="error" showIcon />;


const havePermission = () => {
  return false;
};

const havePermissionAsync = new Promise((resolve,reject)=>{
  // Call reslove on behalf of passed
  setTimeout(()=>reslove(),1000)
});

ReactDOM.render(
  <div>
    <Authorized authority="admin" noMatch={noMatch}>
      <Alert message="user Passed!" type="success" showIcon />
    </Authorized>
    <Authorized authority={['user','admin']} noMatch={noMatch}>
      <Alert message="Use Array as a parameter passed!" type="success" showIcon />
    </Authorized>
    <Authorized authority={Havepermission} noMatch={noMatch}>
      <Alert message="Use function as a parameter passed!" type="success" showIcon />
    </Authorized>
    <Authorized authority={havePermissionAsync} noMatch={noMatch}>
      <Alert message="Use Promise as a parameter passed!" type="success" showIcon />
    </Authorized>
  </div>
  mountNode,
);


如今咱们再回头分析代码。

Authorized组件的authority属性支持:

一、 字符串。应用场景为当你只想一个角色有权限使用该组件的时候。
二、数组。 应用场景为当你想多个角色有权限使用该组件的时候。
三、函数。当你的业务须要使用函数的时候使用。
四、 Promise 。当你须要使用promise的时候使用。



Authorized组件的noMatch属性是支持嵌入其它组件的,这样你能够放提示信息的组件,甚至是跳转到登录页的Redirect组件像这样:
const noMatch = <Redirect exact from="/" to="/user/login"/>;