这就是问题所在。
我希望根据axios实例的请求和响应注册拦截器来捕获错误。我有一个命名为wrapper的withErrorHandler组件,它可以处理错误逻辑。
每当发送HTTP请求和HTTP响应中出现错误时,我都需要更新状态。我需要在调用render方法或componentDidMount之前注册拦截器。
此withErrorHandler组件的任务是显示带有错误消息的覆盖/模式。覆盖/模式根据this.state.error的值有条件地显示,该值可以是null,也可以是从HTTP请求返回的对象。我能够做到这一点的唯一方法是在componentWillMount方法中注册拦截器。
如果我尝试在constructor中注册拦截器,错误覆盖/模式不会显示,因为(我认为)不允许我在constructor中更新拦截器所做的状态。
const withErrorHandler = (WrappedComponent, axios) => {
return class extends Component {
state = {
error: null,
};
constructor() {
super();
this.reqInterceptor = axios.interceptors.request.use((req) => {
this.setState({ error: null }); // the interceptor is updating state in the constructor
return req;
});
this.resInterceptor = axios.interceptors.response.use(
(res) => res,
(error) => {
this.setState({ error: error });
}
);
}
componentWillUnmount() {
axios.interceptors.request.eject(this.reqInterceptor);
axios.interceptors.response.eject(this.resInterceptor);
}
errorConfirmedHandler = () => {
this.setState({ error: null });
};
render() {
return (
<Auxiliary>
<Modal
show={this.state.error}
modalClosed={this.errorConfirmedHandler}
>
{this.state.error ? this.state.error.message : null}
</Modal>
<WrappedComponent {...this.props} />
</Auxiliary>
);
}
};
};这不起作用,我没有得到我的错误覆盖/模式。
正如我所说的,如果我在componentDidMount方法中执行此操作,它将不起作用。我能让它工作的唯一方法就是使用componentWillMount,正如你所知,它已经被折旧了。
无论我走到哪里,我都被告知我应该用constructor替换componentWillMount,但是构造函数不起作用。这里的解决方案是什么?
发布于 2020-07-30 04:46:53
目前,不能在构造函数中设置状态,因此这不起作用。
https://stackoverflow.com/questions/62766040
复制相似问题