反应原生是否支持.error()函数?(Does react native supports .error() function?)

编程入门 行业动态 更新时间:2024-10-17 19:21:10
反应原生是否支持.error()函数?(Does react native supports .error() function?)

我试图处理“网络请求失败”错误(我已经允许来自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()
            }); 
  
 

Im trying to handle a "Network request failed" error (I already allowed unsecured connections from Xcode), But when i try to do something inside the .error() function it crashes and says: .error is not a function; The fetch() works already. here's an example of it, Im trying to run this code after a fetch function.

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()
            }); 
  
 

最满意答案

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() });

React's fetch method returns a Promise, which doesnot have .error() method. Instead it has .catch() method to catch all errors when fetch fails.

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() });

更多推荐

本文发布于:2023-07-16 12:54:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1128658.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   react   error   function   supports

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!