【发布时间】:2026-01-03 07:50:02
【问题描述】:
我正在尝试通过获取请求从服务器获取一些数据。 有时网络会出现故障或发生类似的其他事情,我希望有一个超时以防止进一步的错误并获得更好的体验。
实际上我想等待 20 秒,如果没有得到任何响应,我想显示错误并中断获取请求。
我有一个加载模式,我可以通过超时关闭它,但我也想中断获取请求。
这是我的获取请求代码:
_testPress = async () => {
//setTimeout(() => {this.setState({loading: false})}, 20000)
this.setState({loading : true})
fetch(getInitUrl('loginUser'), {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
password : this.state.password,
email : this.state.emailAddress,
}),
}).then(response => Promise.all([response.ok, response.status ,response.json()]))
.then(([responseOk,responseStatus, body]) => {
if (responseOk) {
//console.log(responseOk, body);
this._signInAsync(body.token);
// handle success case
} else {
console.log(responseStatus);
this.setState({
showAlert : true,
alertType : true,
alertMessage : body.message
});
}
})
.catch(error => {
console.error(error);
// catches error case and if fetch itself rejects
});
}
我使用 setTimeout 关闭加载模块,但它不会停止我希望它在 20 秒后停止的实际请求。
请帮助我提供您的建议。 谢谢。
【问题讨论】:
标签: react-native