React-Native检查图片网址 [英] React-Native check image url

查看:60
本文介绍了React-Native检查图片网址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试检查图像的URL是否为404.问题在于该函数返回的是未定义的.为什么会这样?

I am trying to check if the url of an image is 404 or not. The problem is that the function is returning undefined. Why is this happening?

如果我console.log记录res的状态,它的确显示404,因此if语句正在执行.

If I console.log the status of the res it does show 404 so the if statement is being executed.

function checkImageURL(url){
 fetch(url)
    .then(res => {
    if(res.status == 404){
      console.log(res.status)
      return <Image source={require('./Images/default.png')}/>
    }else{
      return <Image source={{uri: `${url}`}}  />
   }
 })
}

推荐答案

您不会在错误响应中返回任何内容.

you are not returning anything on error response.

添加.catch并返回一个组件或其中的null.例如

add .catch and return a component or null in that. for eg

function checkImageURL(url){
 fetch(url)
    .then(res => {
    if(res.status == 404){
      return <Image source={require('./Images/default.png')}/>
    }else{
      return <Image source={{uri: `${url}`}}  />
   }
 })
.catch(err=>{return <Image source={require('./Images/default.png')}/>})
}

这篇关于React-Native检查图片网址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆