[英]How can I rewrite my method to async/await?
In my react app I'm making a post request to the server with the help of axios: 在我的react应用程序中,我正在axios的帮助下向服务器发出发布请求:
onSubmit = (results) => {
axios.post("http://localhost:8080/simulate/", results)
.then( (response) => this.setState({results: response.data.results}))
.catch( (error) => this.setState({results: error.response.data, hasError: true})
);
}
How can I rewrite this method to async/await
? 如何将这种方法重写为
async/await
?
onSubmit = async (results) => {
try {
const response = await axios.post("http://localhost:8080/simulate/", results)
this.setState({results: response.data.results})
} catch (error) {
this.setState({results: error.response.data, hasError: true})
}
}
If you don't want to use Axios, you may use the fetch api : 如果您不想使用Axios,则可以使用fetch api :
onSubmit = async (results) => {
try {
const response = await fetch("http://localhost:8080/simulate/", {
method: 'POST',
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(results)
})
const { data } = await response.json()
this.setState({results: data.results})
} catch (error) {
this.setState({results: error.response.data, hasError: true})
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.