gpt4 book ai didi

javascript - React 中基于 Angular 色的授权中的 HOC 错误

转载 作者:行者123 更新时间:2023-12-02 22:15:41 26 4
gpt4 key购买 nike

我一直在尝试实现 Role Based Authorization in React如下

在authorization.js中,检查具有其 Angular 色的登录用户是否被允许访问该页面:

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'

有什么建议吗?

最佳答案

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

return class WithAuthorization extends React.Component {

并从

更改行

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

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

关于javascript - React 中基于 Angular 色的授权中的 HOC 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59392168/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com