我一直在尝试在 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'
有什么建议么?