Reactjs 来自React组件的React post请求
我在React组件中有一个函数:Reactjs 来自React组件的React post请求,reactjs,asynchronous,async-await,axios,Reactjs,Asynchronous,Async Await,Axios,我在React组件中有一个函数: verifyInputAndRequest(){ var formData = new FormData(); formData.append("username", this.state.username); formData.append("password", this.state.password); var reply = performPostRequest("linkRequest/", formData)
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
我理解这是由于同步执行
如何处理呢
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);
})
}
}