首页 > 解决方案 > 从存储为 base64 的 JSON 渲染图像以及 React-Native 中的其他数据

问题描述

我有一个我的应用程序从 api 检索的 JSON 文件

它包含名称位置和其他信息以及 base64 编码的图像

[ { meta: { views: 0, tapped: 0, favs: 0, priority: 0 },
    img: { data: [Binary] },
    special: true,
    _id: 5cace9fbeb520a4d8833bc1b,
    date: 2019-04-09T00:00:00.000Z,
    title: 'Test',
    url: 'http://goole.com',
    body: 'Oh it chaned',
    published: false,
    category: 'Sports',
    location: 'dafasfasf',
    __v: 0,
    publishDate: 2019-04-09T18:30:00.000Z,
    subCategory: 'Footabll' },
  { meta: { views: 0, tapped: 0, favs: 0, priority: 0 },
    img: { data: [Binary] },
    special: true,
    _id: 5cacf8e54b578827e8425c83,
    date: 2019-04-02T00:00:00.000Z,
    title: 'Testasd',
    url: 'http://google.com',
    body: 'wadwadwad',
    published: false,
    category: 'Sports',
    location: 'Random',
    subCategory: 'Footabll',
    __v: 0,
    publishDate: 2019-04-09T18:30:00.000Z },

它看起来像这样

我无法在本机反应中渲染图像

我得到 Objects are not valid as a React Child found object with keys{data} 我知道这是一个对象,因此正在发生此错误,但我无法找到解决方案(它告诉我在迭代每个键时我想访问特定的密钥)。

这是我在渲染中调用的函数

viewfunc(){



return(
  this.state.dataSource.map((item)=>{

    return(

    < View key={Math.random()} style={styles.slide3}>

      <Text style={styles.text}>{item.title}</Text>
      <Image
      style={{
        width: 51,
        height: 51,
        resizeMode: 'contain',
      }}
      source={{
        uri:
          'data:image/png;base64,${item.img.data}',
      }}
    />
      <Text style={styles.body}>{item.body}</Text>

    </View>)

}
))}
))}

我无法渲染这个img,而且如果我尝试通过{item.img.data}在文本字段中打印base64,它返回的对象无效..错误我可以访问元数据,{item.meta.views} 请我需要帮助!

编辑

这就是我在将图像推送到数据库时对其进行编码的方式

var newImg = fs.readFileSync(req.file.path);
var encImg = newImg.toString('base64');

这个也试过

  <Image
        style={{
          width: 51,
          height: 51,

        }}
        source={{
          uri:
            `data:image/png;base64,`+item.img.data,
        }}
      />

还没渲染。。

标签: androidnode.jsreactjsreact-nativereact-native-android

解决方案


使用带反引号的字符串插值:

`data:image/png;base64,${item.img.data}`


推荐阅读