在我的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})
);
}
如何将这种方法重写为async/await
?
答案 0 :(得分:2)
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})
}
}
如果您不想使用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})
}
}