繁体   English   中英

React Native:尝试从 Cloud Firestore 获取图像时出现错误

[英]React Native: I am getting error while trying to get image from cloud firestore

我得到 source.uri 不应该是一个空字符串。 我该如何解决这个问题?

我正在使用 google cloud firestore 将所有图像存储在那里并将其呈现在我的应用程序中,然后出现此错误,我不知道如何修复它,请帮我解决这个问题。

这是我的代码:

import React from 'react';
import {
  TouchableOpacity,
  Image,
  View,
  Text
} from 'react-native';
import storage from '@react-native-firebase/storage';
import styles from '../styles/Android.style';

class Catalog extends React.Component {
  constructor(props) {
    super(props)

    this.state = {
      image : ''
    }
  }

  retrieveImages = async () => {
    const url = await storage()
      .ref('/catalogs/web_hi_res_512.png')
      .getDownloadURL();
    this.setState({image : url})
  }

  componentDidMount() {
    this.retrieveImages()
  }

  render() {
    return (
      <View style={styles.homeContainer}>
      <TouchableOpacity style={styles.catalogItem}>
        <View>
          <Image
            source={{uri: this.state.image}}
            style={styles.catalogImage}
          />
        </View>
        <View style={styles.descriptionContainer}>
          <Text style={styles.descriptionPrice}>Ini teks</Text>
          <Text style={styles.descriptionAddress}>Ini deskripsi</Text>
        </View>
      </TouchableOpacity>
      </View>
    );
  }
}

export default Catalog;

您已在组件 state 中使用空字符串 ( image: '' ) 进行了初始化,因此当组件加载时, source.uri将使用''进行初始化,因为那时您还没有从云 Firestore 获取图像。

一种解决方案是使用一些默认图像初始化 state 并在您的图像组件中显示该图像,直到从云中下载图像。

当您将图像 state 初始化为空字符串时,您会收到此错误。

有条件地渲染图像组件很容易解决这个问题。 做就是了:

<View style={styles.homeContainer}>
  <TouchableOpacity style={styles.catalogItem}>
    <View>
      {image !== '' ? (
       <Image
        source={{uri: this.state.image}}
        style={styles.catalogImage}
       />
      ) : null}
    </View>
    <View style={styles.descriptionContainer}>
      <Text style={styles.descriptionPrice}>Ini teks</Text>
      <Text style={styles.descriptionAddress}>Ini deskripsi</Text>
    </View>
  </TouchableOpacity>
  </View>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM