在ajax调用之后,reactjs更新状态

时间:2016-08-29 12:44:19

标签: javascript jquery ajax reactjs

当我从ajax调用中收到错误时,我想更新我的状态。

我的代码:

var EmailForm = React.createClass({

    getInitialState: function(){
      return {
          password:'',
          email: '',
          errors: ''
      };
    },

    componentDidMount: function() {
        this.serverRequest = $.get('/accounts/email-form/', function (result) {
          var userInfo = result;
          this.setState({
            email: userInfo.email
          });
        }.bind(this));
    },

    submit: function (e){
      var self;

      e.preventDefault()
      self = this;

      console.log(this.state);

      var data = {
        password: this.state.password,
        email: this.state.email,
        CSRF: csrftoken
      };

      // Submit form via jQuery/AJAX
      function csrfSafeMethod(method) {
            // these HTTP methods do not require CSRF protection
            return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
      }
      $.ajaxSetup({
            beforeSend: function(xhr, settings) {
                if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
                    xhr.setRequestHeader("X-CSRFToken", csrftoken);
                }
            }
      });
      $.ajax({
        type: 'POST',
        url: '/accounts/email-form/',
        data: data,
        datatype: JSON
      })
      .done(function(data) {
        toastr.success('Profile updated');
      })
      .error(function(jqXhr) {
          var error = jqXhr.responseJSON; //How can I append this errors to my errors state ?
          toastr.error('There is some errors in your request');
      });
    },

    passwordChange: function(e){
      this.setState({password: e.target.value});
    },

    emailChange: function(e){
     this.setState({email: e.target.value});
    },

    render: function() {
        return (
            <form onSubmit={this.submit}>
                <div className="form-half">
                    <label htmlFor="password" className="input-label">Current Password</label>
                    <BasicInputPassword valChange={this.passwordChange} val={this.state.password}/>
                    <span className="form-error is-visible">{this.state.errors.password}</span>
                </div>
                <div className="form-half">
                    <label htmlFor="email" className="input-label">New email</label>
                    <BasicInput valChange={this.emailChange} val={this.state.email}/>
                    <span className="form-error is-visible">{this.state.errors.email}</span>
                </div>
                 <button type="submit" className="button secondary" >Submit</button>
            </form>
        );
    }
});

我在错误变量中有响应错误。如何使用此json更新状态错误并显示例如state.errors.email easy?这可能吗?

3 个答案:

答案 0 :(得分:0)

$.get('some.php')
    .done(function(msg){  })
    .fail(function(xhr, status, error) {
       this.setState({});///here <===
    }).bind(this);

   $.ajax({
      type: "GET",
      url: "test.com",
      success: function(msg){
            alert( "Data Saved: " + msg );
      },
      error: function(XMLHttpRequest, textStatus, errorThrown) {
         alert("some error");
      }
    });

您必须使用.fail(),然后才能访问error中的.fail()并存储状态。

答案 1 :(得分:0)

使用this.setState()

var that = this;
$.ajax({
        type: 'POST',
        url: '/accounts/email-form/',
        data: data,
        datatype: JSON
      })
      .done(function(data) {
        toastr.success('Profile updated');
      })
      .fail(function(xhr, status, error) {
          that.setState({
          //assign error to whatever you want under `state`
          });
      });

*确保this指向正确的范围。或者使用arrow functions作为词汇this

答案 2 :(得分:0)

你可以这样做。

const self = this;
$.get('api-url')
.done(function(msg){
  // some work  
 })
.fail(function(xhr, status, error) {
   self.setState({error: xhr.responseJSON });
});

当此上下文发生变化时,您可以先将变量分配给变量,以避免与上下文混淆。