javascript - HOC 和标准组件之间的主要区别是什么?我什么时候应该正确使用它们?

标签 javascript reactjs react-native

我对高阶组件标准组件很好奇,我该怎么办。

根据文档所述:

高阶组件:

A higher-order component (HOC) is an advanced technique in React for reusing component logic. HOCs are not part of the React API, per se. They are a pattern that emerges from React’s compositional nature.

标准组件:

Components let you split the UI into independent, reusable pieces, and think about each piece in isolation. This page provides an introduction to the idea of components.

我只是认为它们都是可重用的渲染代码。

那么HOC标准组件的优缺点是什么,我什么时候应该正确使用它们之一?

欢迎任何建议

最佳答案

当然!标准组件是一个可重用的组件,甚至HOC也是一个组件,用于重用组件逻辑。

高阶组件只是一个包装另一个组件的 React 组件。 React HOC 模式通常作为函数实现,它基本上是一个类工厂,在受 Haskell 启发的伪代码中具有以下签名

hocFactory:: W: React.Component => E: React.Component

Where W (WrappedComponent) is the React.Component being wrapped and E(Enhanced Component) is the new, HOC, React.Component being returned.

The “wraps” part of the definition is intentionally vague because it can mean one of two things:

  • Props Proxy: The HOC manipulates the props being passed to the WrappedComponent W.
  • Inheritance Inversion: The HOC extends the WrappedComponent W.

在高层次上 HOC 使您能够:

  • Prop 操作
  • 代码重用、逻辑和引导抽象
  • 状态抽象和操作
  • 渲染劫持

使用标准组件时无法更改。

所以基本上,如果你需要操纵 Prop 并干扰渲染过程,你必须使用 HOC 而不是标准组件。

HOC 的简单示例

import React from 'react';
import AuthService from '../services/AuthService';

const AuthContext = React.createContext();

export default class AuthProvider extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            authService: new AuthService(),
            loggedIn: false, 
            userSigninFetching: true,
            userSigninError: '',
            user: null
        }   
    }

    componentWillMount() {
        this.processAuthState();
    }

    processAuthState = () => {
        this.setState({ userSigninFetching: true });

        const user = JSON.parse(localStorage.getItem('user'))

        if (!user) {
            this.setState({
                loggedIn: false,
                userSigninFetching: false,
                userSigninError: "Login Failed",
                user: null
            });
            return;
        } 

        this.setState({
            loggedIn: true,
            userSigninFetching: false,
            userSigninError: "Successfully Logged In",
            user: user
        });
    }

    render() {
        return (
            <AuthContext.Provider value={{ authState: this.state }}>
                {this.props.children}
            </AuthContext.Provider>
        )
    }
}


export const withAuth = (BaseComponent) => class AuthComponent extends React.Component {
    render() {
        return (
            <AuthContext.Consumer>
                {(context) =>  (
                    <BaseComponent
                        {...this.props}
                        authState={context ? context.authState : {
                            loggedIn: false,
                            userSigninFetching: false,
                            userSigninError: "",
                            user: null
                        }}
                    />
                )}
            </AuthContext.Consumer>
        )
    }
}

现在让我们用 withAuth 包装您的组件,以从组件本身访问身份验证状态。

import { withAuth } from '../providers/AuthProvider';

const myComponent = ({ authState }) => {
    return (
        <div>Custom component</div>
    );
}

export default withAuth(myComponent);

现在您可以在 myComponent 中访问应用程序身份验证状态。

block 引用

Here is the react guide for HOC

Also a good blog to dive in to depth of HOC

关于javascript - HOC 和标准组件之间的主要区别是什么?我什么时候应该正确使用它们?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56219243/

相关文章:

reactjs - 开 Jest : How to test function that calls bind(this)

react-native - 有没有办法在不弹出的情况下删除react-native中的默认权限?

javascript - 调用方法时出错 'addNewDriveToSadranTable' : Internal server error [500]

javascript - Electron - 更新窗口消息

javascript - 根据函数返回值更新dom

javascript - 使用 extract-text-webpack-plugin 和在 HTML header 中链接合并的 CSS 文件有什么区别?

javascript - silverstripe-module yeoman 生成器中的 JS 意外 token 错误

javascript - Nodejs - 如何将数据从 html 发送到 hapi

android - 从 android studio 运行选项在设备上运行(而不是 react-native run-android 命令)

android - 为什么关闭或按“后退”按钮时我的React Native Android应用程序崩溃?