首页 > 解决方案 > React Native:将图像源声明为函数时出现问题?

问题描述

这是我试图用 React Native 做的事情:

  1. 从数据库中获取图像 URL 数据。
  2. 检查图像是否存在于存储中。
  3. 如果图像存在,则渲染它。如果不是,则渲染占位符图像。

基本上,我声明了一个函数来执行步骤 2 和 3,并将其作为 Image 组件中的源。但是,即使目标图像存在于带有 URL 的存储中,Image 组件也不会渲染任何图像。

这里可能发生了什么?这是我正在使用的代码。不明白为什么这段代码不起作用……也许是语法错误?什么可能是修复/更好的方法来做到这一点?

//The function to check if the image actually exists and return placeholder if not
const checkImageURL = (url) => {
    const placeholder_url='url_of_placeholder_image';
    fetch(url)
       .then(res => {
       if(res.status == 404){
         return placeholder_url;
       }
       else{
         return url;
      }
    })
   .catch(err=>{return placeholder_url})
}

//The way I declared the source for the image
<Image source={uri:checkImageURL(url)} style={style.mainImage}/>

标签: react-native

解决方案


远程 URL 的 source prop 必须是一个对象,所以你需要再添加一个花括号

<Image source={{uri:checkImageURL(url)}} style={style.mainImage}/>

有关道具中花括号的更多信息here


推荐阅读