setState不更新状态数组

时间:2017-05-30 06:06:56

标签: javascript ajax reactjs

用户点击按钮,onClick我发出ajax帖子请求,并且我正在尝试在我的请求的.then().catch()阶段设置State。我一直在

  

“只能更新已安装或安装的组件。这通常意味着   您已在未安装的组件上调用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>
    )
 }
})

1 个答案:

答案 0 :(得分:3)

你不应该直接改变状态。

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);
},