如何在反应js中重试失败的ajax?

时间:2017-02-06 10:35:13

标签: javascript jquery ajax reactjs

我用react js创建了应用程序。在这个应用程序中,我有一个帖子请求。如果此请求失败,我想在错误回调时回忆这个​​请求。如何用ajax实现?请检查以下代码,

handleSubmit() {
    var resObj = {
        "TITLE":this.state.title,
        "NAME":this.state.name
    };
    $.ajax({
        url:url+"activity"+id,
        type:"PUT",
        data:JSON.stringify(resObj),
        dataType:'json',
        headers:{"content-type": "application/json", "Authorization":localStorage.getItem('token')},
        success:function(data, status){
        }.bind(this),
        error:function(xhr, status, err, data){
            if(xhr.status == 401 || xhr.status == 500 || xhr.status == 200) {
                $.ajax(this);
            }
        }.bind(this)
    });
}

1 个答案:

答案 0 :(得分:0)

你不能以这种方式使用$ .ajax(this)。 $ .ajax方法需要一个对象,就像你在第一次调用时所做的那样。在您的代码中,'this'与您的react组件绑定在一起。我认为有多种解决方案可以解决您的问题。一个简单的方法是你可以再次调用该函数。

class RetryHandler{
    constructor(option){
      const defaultOptions = {
         // you can add default options here like maxRetry = 10, 
      };
      this.options = Object.assign({},defaultOptions,option);
      this.doSubmit();
    }

    doSubmit(){
      $.ajax({
        url:this.options.url,
        type:this.options.type,
        data:this.options.data,
        dataType:this.options.dataType,
        headers:this.options.headers,
        success:this.options.success,
        error:function(xhr, status, err, data){
            let args = Array.prototype.slice.call(arguments);
            args.push(this.doSubmit.bind(this));
            this.options.error.apply(this,args);
        }.bind(this)
      })

    }
 }

}



class App extends Component{

    handleSubmit() {

          new RetryHandler({
          url:"/mia",
          type:"POST",
          data:{name:"hello"},
          success:function(data, status){},
          error:function(xhr, status, err ,retry){
              setTimeout(function(){
                retry(); <-- on your error callback, you now have a retry function available, you just simply call this if you want to retry
              },1000);
          }
          });

    }

    render(){
      return <div onClick={this.handleSubmit.bind(this)}>Hello</div>
    }
  }