仅允许用户访问 his/her 仪表板

Allow user to access only his/her dashboard

我有四种不同的布局。

AdminLayout 是管理相关页面的父级和用户的 UserLayout 相关等等。我已经使用高阶组件来检查是否 用户未经身份验证,将他们重定向到主页。还有一个条件。也就是说,如果用户已通过身份验证,但如果用户的角色不是管理员并且用户尝试访问 AdminDashboard,则 he/she 应该被重定向到主页,并且与其他页面类似。但是 Agent 可以访问 UserDashboard。

我得到的角色的形式是

user_role = ['superadmin'] or ['enduser'] or ['agent'] or 
['enduser', 'agent'].

除了代理也可以访问代理仪表板和用户仪表板外,不应访问其他仪表板。对于未经身份验证的用户,我可以在不登录的情况下访问仪表板时重定向到主页

重定向到未经身份验证的用户的代码正在运行,我已经按照以下方式完成了

const Redirection = prop => WrappedComponent => {
  return class Redirection extends React.PureComponent {
    render() {
      const user_instance = JSON.parse(localStorage.getItem("user"));
      if (!user_instance) {
        return <Redirect to="/" />;
      } else {
        return <WrappedComponent {...this.props} />;
      }
    }
  };
};

export default props => WrappedComponent =>
  connect(null, mapDispatchToProps)(Redirection(props)(WrappedComponent));

AdminLayout

class AdminLayout extends React.Component {
  render() {
    return (
      <div>
        {this.props.children}
      </div>
    );
  }
}

export default Redirection()(AdminLayout);

我从 localStorage 得到的 user_role 是 JSON.parse(localStorage.getItem("user"))['userInfo]['user_role']

你可以使用 lodash intersection 来做到这一点。这是它的link

https://lodash.com/docs/4.17.4#intersection

对于您的情况,检查将在

之后进行
if (
        user_instance &&
        intersection(prop, user_instance["userInfo"]["user_role"])
          .length > 0
      ) {
        return <WrappedComponent {...this.props} />;
      } else {
        return <Redirect to="/" />;
      }

您可以粘贴以下内容snippet.Also不要忘记查看 lodash 文档,因为它对您的后续工作非常有帮助