首页 > 解决方案 > 在 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>
            );
        }
    }
}

标签: reactjsaxiosreact-lifecycle-hooks

解决方案


推荐阅读