[英]How can I write React component that returns a class component as a functional component?
我的目标:
我目前正在实现一个AuthUserRole
HOC 组件来处理用户角色:经理和员工。 我正在使用本教程这样做,但他们使用功能组件来返回 class 组件。
我的问题:
如何编写此 HOC 功能组件以返回功能组件而不是 class 组件? 或者,还有更好的方法?
返回 Class 组件的功能组件:
// Imports: Dependencies
import React, { Component } from 'react';
import { connect } from 'react-redux';
// Component: Authorization
const AuthUserRole = (WrappedComponent, allowedRoles) => {
class With AuthUserRole extends Component {
render() {
const userType = this.props.userType;
if (allowedRoles.includes(userType)) {
return <WrappedComponent {...this.props} />;
}
else {
return <h1>You are not allowed to view this page!</h1>;
}
}
}
const mapStateToProps = state => ({ user: state.login.userName, userType: state.login.userType });
return connect(mapStateToProps)(AuthUserRole);
};
// Exports
export default AuthUserRole;
App.js(使用 HOC 的地方):
<BrowserRouter history={history}>
<Switch>
{/* LANDING */}
<Route path="/" component={Landing} exact />
{/* APP */}
<PrivateRoute path="/student/dashboard" component={Authorization(DashboardStudent,["Student"])}/>
<PrivateRoute path="/admin/dashboard" component={Authorization(DashboardAdmin,["Admin"])}/>
{/* LOGIN */}
<Route path="/login" component={UserLogin}/>
{/* NOT FOUND */}
<Route path="" component={NotFoundPage} />
</Switch>
</BrowserRouter>
为了返回一个 function 组件,只需返回一个 function 的props
const AuthUserRole = (WrappedComponent, allowedRoles) => {
return (props) => {
...
}
}
推荐的最佳实践是使用useSelector
挂钩而不是mapStateToProps
和connect
。 所以还有一些其他的调整。
import React, { ComponentType } from 'react';
import { useSelector } from 'react-redux';
// Component: Authorization
const AuthUserRole = <Props extends {}>(WrappedComponent: ComponentType<Props>, allowedRoles: string[]) => {
return (props: Props) => {
// TODO: add your app's state type
const userType = useSelector(state => state.login.userType);
const user = useSelector(state => state.login.userName); // where is this used?
if (allowedRoles.includes(userType)) {
return <WrappedComponent {...props} />;
}
else {
return <h1>You are not allowed to view this page!</h1>;
}
}
};
// Exports
export default AuthUserRole;
我添加了类型注释,因为您标记了这个typescript
,但我在当前代码中看不到任何类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.