0

我一直在尝试在 React 中实现基于角色的授权,如下所示

在 authorization.js 中,检查是否允许登录用户及其角色访问该页面:

import React from "react";

const Authorization = (WrappedComponent, allowedRoles) => {
  return class WithAuthorization extends React.Component {
    constructor(props) {
      super(props);

      this.state = {
        user: {
          name: "vcarl",        
          role: "Admin"
        }
      };
    }
    render() {
      const { role } = this.state.user;
      if (allowedRoles.includes(role)) {
        return <WrappedComponent {...this.props} />;
      } else {
        return <h1>No page for you!</h1>;
      }
    }
  };
};

export default Authorization;

在 App.js 中

render() {
    const accounts = Authorization(["SuperAdmin", "Admin"]);

    return (
      <StateContext.Provider value={{ ...this.state }}>
        <Router>                   
            <Route
              exact
              path="/accounts"
              component={accounts(Accounts)}
            />         
        </Router>
      </StateContext.Provider>
    );
  }

在 Accounts.js 中:

import React, { Component } from "react";

class Accounts extends Component {
  render() {
    return <div>Accounts page</div>;
  }
}

export default Accounts;

但得到错误:

TypeError: Class constructor WithAuthorization cannot be invoked without 'new'

有什么建议么?

4

1 回答 1

1

您正在尝试返回类但是在 React 哲学组件中应该返回 JSX 或修改后的子组件所以您需要删除

return class WithAuthorization extends React.Component {

并从

return <WrappedComponent {...this.props} />;

return <>{this.props.children}</>;

于 2019-12-18T13:00:20.833 回答