我为 React 编写了函数式和基于类的高阶组件函数。基于类的版本有效,而使用钩子的功能形式的精确翻译不起作用。有人可以解释我哪里出错了,下面提到了两个代码块。
基于类的 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;
基于功能的 HOC
import React, {useState, useEffect} from "react";
import Modal from "../components/UI/Modal/Modal";
const withErrorHandler = (WrappedComponent, axios) => {
return (props) => {
const [error, setError] = useState(null);
const requestInterceptor = axios.interceptors.request.use((req) => {
setError(null);
return req;
});
const responseInterceptor = axios.interceptors.response.use(
(res) => res,
(err) => {
setError(err);
}
);
useEffect(() => {
return () => {
axios.interceptors.request.eject(requestInterceptor);
axios.interceptors.response.eject(responseInterceptor);
};
}, [requestInterceptor, responseInterceptor]);
const errorConfirmedHandler = () => {
setError(null);
};
return (
<React.Fragment>
<Modal showModal={error ? true : false} closeModal={errorConfirmedHandler}>
{error ? error.message : null}
</Modal>
<WrappedComponent {...props} />
</React.Fragment>
);
};
};
export default withErrorHandler;