在 componentDidMount 中发出 http 请求并更改那里的状态,但它不会重新渲染我的 DOM,这有条件地取决于状态

问题描述

由于 componentwillMount() 已弃用,我在 componentDidMount() 中发出 HTTP 请求并根据响应更新那里的状态。虽然 componentDidMount() 在 render() 方法之后运行,但是在 componentDidMount 中使用 this.setState() 应该再次调用 render 方法。因此,如果请求中存在某些错误,则应重新呈现有条件地依赖状态中的错误属性的模态组件。但是状态没有改变,因此我的 Modal 组件永远不会被渲染。有人可以帮忙吗??

const withErrorHandler = (WrappedComponent,axios) => {
    return class extends Component {

        state = {
            error: null
        }
        
        componentDidMount () {
            axios.interceptors.request.use(req => {
                this.setState({
                    error: null
                });
                return req;
            });
            axios.interceptors.response.use(res => res,error => {
                this.setState({
                    error: error
                });
            });
        }

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

        render() {

            return (
                <Aux>
                    <Modal show={this.state.error} modalClosed={this.errorConfirmedHandler}>
                        {this.state.error ? this.state.error.message : null}
                    </Modal>
                    <WrappedComponent {...this.props} />
                </Aux>
            );
        }
    }
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)