[英]Error handling for an api request in React
我试图处理 api 调用的错误。 目标是仅在后端成功响应时显示按钮。 否则不显示按钮。 但是,即使出现错误,按钮也会显示。 这是我的代码:
handleSubmit = (e) => {
const {
firstName, lastName, country, region, address, city, actions
} = this.props;
e.preventDefault();
verify(firstName, lastName, address, city, region, country)
.then((data) => {
actions.showSuccessNotification(data);
}, () => {
this.setState({
...this.state,
triggerShowButton: true
});
});
}
这是我渲染按钮的地方:
{ (triggerShowButton ) && <Button className={classes.button} onClick= disabled={kycLevelTwoVerified} variant="contained" color="primary">Proceed</Button> }
function
核实
是直接来自另一个文件的 function。 我导入了它。 这里是:
async function verifyLevelOne(firstName, lastName, addressLine1, city, region, country) {
const options = {
method: 'POST',
headers: {
'content-type': 'application/json'
},
data: {
firstName,
lastName,
addressLine1,
city,
region,
country
},
url: `${BASE}/level1`
};
return axios(options);
}
上面的代码可能不相关,但我只是在这里显示以防万一。 有什么方法可以使按钮仅在成功响应时可见?
它总是真实的,因为你在告诉它
, () => {
this.setState({
...this.state,
triggerShowButton: true
});
您可能应该放置一个if
语句来检查服务器的状态或使用.catch()
出现错误
像这样
verify(firstName, lastName, address, city, region, country)
.then((data) => {
actions.showSuccessNotification(data);
},() => {
this.setState({
...this.state,
triggerShowButton: true
}).catch((error) => {
//handle error
console.log(error)
})
或替代解决方案
verify(firstName, lastName, address, city, region, country)
.then((data) => {
actions.showSuccessNotification(data);
},() => {
if(dataIsVerified){ // dataIsVerified = you need to check if the data is ok it's up to you i just made it up
this.setState({
...this.state,
triggerShowButton: true
})
} else {throw "error"}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.