我试图处理“网络请求失败”错误(我已经允许来自Xcode的不安全连接),但是当我尝试在.error()函数内部执行某些操作时,它会崩溃并说:.error不是函数; fetch()已经有效了。 这是一个例子,我试图在获取函数后运行此代码。
fetch('URL',{
'method': 'POST',
'headers': {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
'body': data}
)
.then((response) => response.json())
.then((responseJson) => {
//Do something
})
.error((error)=>{
console.error(error);
Actions.login()
});
答案 0 :(得分:1)
React的fetch
方法返回Promise,其中没有.error()
方法。相反,它有.catch()
方法来捕获fetch
失败时的所有错误。
fetch('URL', {
'method': 'POST',
'headers': {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
'body': data
})
.then((response) => response.json())
.then((responseJson) => {
//Do something
})
.catch((error) => {
console.error(error);
Actions.login()
});