基于React类的高阶组件有效,但不具有基于函数的钩子

时间:2020-07-09 14:33:33

标签: javascript reactjs react-hooks react-hoc

我为React编写了基于函数和基于类的高阶组件函数。基于类的版本有效,因为带钩子的函数形式的确切翻译不起作用。有人可以解释我哪里出错了,下面提到了两个代码块。

基于类的HOC

loadOptions

基于功能的HOC

import React, { Component } from "react";
import Modal from "../components/UI/Modal/Modal";

const withErrorHandler = (WrappedComponent, axios) => {
  return class extends Component {
    state = {
      error: null,
    };

    componentWillMount() {
      this.reqInterceptor = axios.interceptors.request.use((req) => {
        this.setState({ error: null });
        return req;
      });
      this.resInterceptor = axios.interceptors.response.use(
        (res) => res,
        (error) => {
          this.setState({ error: error.response });
          console.log(error.response)
        }
      );
    }

    componentWillUnmount() {
      axios.interceptors.request.eject(this.reqInterceptor);
      axios.interceptors.response.eject(this.resInterceptor);
    }

    errorConfirmedHandler = () => {
      this.setState({ error: null });
    };

    render() {
      return (
        <React.Fragment>
          <Modal showModal={this.state.error ? true : false} error={this.state.error} closeModal={this.errorConfirmedHandler}>
            {this.state.error ? this.state.error.message : null}
          </Modal>
          <WrappedComponent {...this.props} />
        </React.Fragment>
      );
    }
  };
};

export default withErrorHandler;

0 个答案:

没有答案