简体   繁体   中英

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

I am getting source.uri should not be an empty string. How can i solve this?

I am using google cloud firestore to store all the images there and render it in my app, then this error shows up and i have no idea how to fix it, please help me solve this.

Here is my code:

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;

You have initialised with empty string ( image: '' ) in your component state, so when component will load, source.uri will be initialised with '' because by that time you did not get the image from cloud firestore.

One solution can be to initialise the state with some default image and show that image in your Image component until the image from the cloud is downloaded.

As you have initialised your image state as an empty string, you are getting this error.

Conditionally rendering the image component would easily solve this. Just do:

<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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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