簡體   English   中英

如何編寫返回 class 組件作為功能組件的 React 組件?

[英]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掛鈎而不是mapStateToPropsconnect 所以還有一些其他的調整。

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM