【问题标题】:React post request from react component来自反应组件的反应发布请求
【发布时间】:2018-01-18 01:39:46
【问题描述】:

我在 React Component 中有一个函数:

verifyInputAndRequest(){
    var formData = new FormData();
    formData.append("username", this.state.username);
    formData.append("password", this.state.password);
    var reply = performPostRequest("linkRequest/", formData)
    console.log(reply) //this returns undefined     
    }

}

performPostRequest 函数如下所示:

export function performPostRequest(RequestUrl, data) {
    axios.post(RequestUrl, data)
    .then(function (response) {
        return response;
    })
    .catch(function (error) {
        //handle error
          return error;
    });

}

在执行期间,reply 被记录为undefined

我知道这是由于同步执行造成的。

如何处理?

【问题讨论】:

    标签: reactjs asynchronous async-await axios


    【解决方案1】:
    export function performPostRequest(RequestUrl, data) {
     return new Promise((resolve,reject)=>{
      axios.post(RequestUrl, data)
      .then(function (response) {
        resolve (response);
       })
      .catch(function (error) {
        //handle error
          reject(error);
      });
    })
    }
    

    在验证功能中:-

       verifyInputAndRequest(){
        var formData = new FormData();
        formData.append("username", this.state.username);
        formData.append("password", this.state.password);
        performPostRequest("linkRequest/", formData)
         .then((data)=>{
           var reply = data;
           console.log(reply);
          })
         .catch((err)=>{
          console.log("err",err);
         })
    
        }
    
    }  
    

    【讨论】:

      猜你喜欢
      • 2019-01-05
      • 1970-01-01
      • 1970-01-01
      • 2019-04-03
      • 1970-01-01
      • 2021-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多