用户单击按钮,onClick我发出ajax发布请求,而我正在尝试在请求的.then().catch()阶段设置setState。我不断


  “只能更新已安装或正在安装的组件。这通常意味着
  您已在未安装的组件上调用setState()。这是无人值守。
  请检查ContactForm组件的代码。”


我究竟做错了什么?

const ContactForm = React.createClass({
componentDidMount() {
    this._mounted = true;
},
componentWillMount() {
    this._mounted = false;
},
getInitialState() {
    return {
        formSubmitted: false,
        formSuccess: false,
    }
},
submitForm(info) {
    this.props.setLoading(true);
    axios.post('/contact', info)
        .then(response => {
            this.handleSuccess(response);
        })
        .catch(error => {
            this.handlError(error);
        });
},
handleSuccess(response) {
    console.log(response);
    this.props.setLoading(false);
    this.state.formSubmitted = true;
    this.state.formSuccess = true;
    if (this._mounted) {
        this.setState(this.state);
    }
},
handlError(error) {
    console.log("error")

    this.props.setLoading(false);
    this.state.formSubmitted = true;
    this.state.formSuccess = true;
    if (this._mounted) {
        this.setState(this.state);
    }
    console.log(error);
},
render() {
    console.log(this.state);
    return (
        <div className="col-xs-12 col-sm-12 col-md-5 col-md-offset-1 wow fadeInUp" data-wow-delay="0.3s">
            <div className="form-group">
                {this.state.formSubmitted == false ? <Form submitForm={this.submitForm} /> : null}
                {this.state.formSubmitted && this.state.formSuccess ? <FormSuccess /> : null}
                {this.state.formSubmitted && !this.state.formSuccess ? <FormError /> : null}
            </div>
        </div>
    )
 }
})

最佳答案

您不应该直接改变状态。

handleSuccess(response) {
    console.log(response);
    this.props.setLoading(false);
    if (this._mounted) {
         this.setState({formSubmitted: true, formSuccess: true});
    }
},
handlError(error) {
    console.log("error")

    this.props.setLoading(false);
    if (this._mounted) {
        this.setState({formSubmitted: true, formSuccess: true});
    }
    console.log(error);
},

10-06 04:25
查看更多