【问题标题】:console. error:[time and date here] @firebase/firestore: Firestore(7.2.3): could not reach cloud firestore backend REACT NATIVE安慰。错误:[此处的时间和日期] @firebase/firestore: Firestore(7.2.3): could not reach cloud firestore backend REACT NATIVE
【发布时间】:2020-07-12 09:04:39
【问题描述】:

我希望每个人都过得愉快!顺便说一句,我想寻求你们的帮助,因为我只是在学习如何编码,而且我真的很难。当我没有将存储图像的代码添加到 Firebase 存储时,我的代码正在工作,但是当我添加将图像保存到 Firebase 存储的功能时,我有这个错误 console.错误:[此处的时间和日期]@firebase/firestore:Firestore(7.2.3):无法访问云 Firestore 后端。后端在 10 秒内没有响应。这通常表明您的设备目前没有健康的互联网连接,但是当我尝试删除插入图像的功能时,代码可以正常工作。谁能帮我解决这个问题?

import React, { Component } from 'react';
import {
    StyleSheet, View, Alert, TextInput, Button, Text, Platform, TouchableOpacity, ListView,Dimensions, ActivityIndicator, Image, ScrollView, KeyboardAvoidingView, Picker
} from 'react-native';
import { Actions } from 'react-native-router-flux'; // New code
import firebase from './firebase';
import RNFetchBlob from 'react-native-fetch-blob'
import ImagePicker from 'react-native-image-picker'

// More info on all the options is below in the README...just some common use cases shown here
var options = {
  title: 'Select Avatar',
  storageOptions: {
    skipBackup: true,
    path: 'images'
  }
};

// Prepare Blob support 
const Blob = RNFetchBlob.polyfill.Blob
const fs = RNFetchBlob.fs
window.XMLHttpRequest = RNFetchBlob.polyfill.XMLHttpRequest
window.Blob = Blob



export default class GoldScreen extends Component{

  constructor(props) {
    super(props);
    this.ref = firebase.firestore();
    this.getImage = this.getImage.bind(this)
    this.state = {
      image_uri: 'https://avatars0.githubusercontent.com/u/12028011?v=3&s=200',
      image: '',
      section: '',
      unit: '',
      price: '',
      product: '',
      status: '',
      hasError: false,
      errorText: '',
       isLoading: false,


    };
}

uploadImage(uri, mime = 'application/octet-stream') {
  return new Promise((resolve, reject) => {
    const uploadUri = Platform.OS === 'ios' ? uri.replace('file://', '') : uri
    let uploadBlob = null

    const imageRef = firebase.storage().ref('images').child('image_file_name')


    fs.readFile(uploadUri, 'base64')
      .then((data) => {
        return Blob.build(data, { type: `${mime};BASE64` })
      })
      .then((blob) => {
        uploadBlob = blob
        return imageRef.put(blob, { contentType: mime })
      })
      .then(() => {
        uploadBlob.close()
        return imageRef.getDownloadURL()
      })
      .then((url) => {
        resolve(url)
      })
      .catch((error) => {
        reject(error)
    })
  })
}

getImage(){

  ImagePicker.showImagePicker(options, (response) => {
    console.log('Response = ', response);

    if (response.didCancel) {
      console.log('User cancelled image picker');
    }
    else if (response.error) {
      console.log('ImagePicker Error: ', response.error);
    }
    else if (response.customButton) {
      console.log('User tapped custom button: ', response.customButton);
    }
    else {
      // let source = { uri: response.uri };
      // this.setState({image_uri: response.uri})

      // You can also display the image using data:
      // let image_uri = { uri: 'data:image/jpeg;base64,' + response.data };

    this.uploadImage(response.uri)
      .then(url => { alert('uploaded'); this.setState({image_uri: url}) })
      .catch(error => console.log(error))

    }
  });

}
updateUser = (TextInputValue) => {
  this.setState({ status: TextInputValue })
}



render(){
  if (this.state.isLoading) {
    return (
      <View style={{flex: 1, paddingTop: 20}}>
        <ActivityIndicator />
      </View>
    );
  }
  return (
    <View style={styles.MainContainer}>

      <Text style={{fontSize: 20, textAlign: 'center', marginBottom: 7}}> Add Product </Text>
      <ScrollView 
          keyboardShouldPersistTaps="handled" 
          showsVerticalScrollIndicator={false}>
      <KeyboardAvoidingView enabled >
      <Image
            style={{width: 100, height: 100}}
            source={{uri: this.state.image_uri}}
          />
        <Button
          onPress={this.getImage}
          title="Change Image"
          color="#841584"
        />
 <TextInput

   placeholder="Enter Product"

   onChangeText={ TextInputValue => this.setState({ product : TextInputValue }) }

   underlineColorAndroid='transparent'

   style={styles.TextInputStyleClass}

 />

<TextInput

   placeholder="Enter Price"
   keyboardType={'decimal-pad'}
   onChangeText={ TextInputValue => this.setState({ price : TextInputValue }) }

   underlineColorAndroid='transparent'

   style={styles.TextInputStyleClass}
 />



<Picker 
                   selectedValue={this.state.unit}
                   style={{height: 50, width: 300}}
                   onValueChange={(TextInputValue, itemIndex) =>
                   this.setState({unit: TextInputValue})}>
                     <Picker.Item label = "Select Unit" />
               <Picker.Item label = "Kilo" value = "Kilo" />
               <Picker.Item label = "Each" value = "Each" />
               <Picker.Item label = "Bottle" value = "Bottle" />
               <Picker.Item label = "Pack" value = "Pack" />
               <Picker.Item label = "Sack" value = "Sack" />




            </Picker>


          <Picker 
                   selectedValue={this.state.section}
                   style={{height: 50, width: 300}}
                   onValueChange={(TextInputValue, itemIndex) =>
                   this.setState({section: TextInputValue})}>
                     <Picker.Item label = "Select Section" />
               <Picker.Item label = "Meat" value = "Meat" />
               <Picker.Item label = "Vegetable" value = "Vegetable" />
               <Picker.Item label = "Fruits" value = "Fruits" />
               <Picker.Item label = "Biscuits" value = "Biscuits" />
               <Picker.Item label = "Condiments" value = "Condiments" />
               <Picker.Item label = "Canned Goods" value = "Canned Goods" />
               <Picker.Item label = "Drinks" value = "Drinks" />

               <Picker.Item label = "Diapers/Napkin" value = "Diapers/Napkin" />
               <Picker.Item label = "Frozen Products" value = "Frozen Products" />
               <Picker.Item label = "Junk Foods" value = "Junk Foods" />
               <Picker.Item label = "Milk" value = "Milk" />
               <Picker.Item label = "Soap/Shampoo" value = "Soap/Shampoo" />
               <Picker.Item label = "Pesonal Items" value = "Pesonal Items" />
               <Picker.Item label = "Pasta/Noodleslete" value = "Pasta/Noodles" />




            </Picker>


<TextInput

   placeholder="Enter Description"
   multiline={true}
   numberOfLines={4}
   onChangeText={ TextInputValue => this.setState({ description : TextInputValue }) }

   underlineColorAndroid='transparent'

   style={styles.TextInputStyleClass}
 />


 <TextInput

   placeholder="Enter image"

   onChangeText={ TextInputValue => this.setState({ image_uri : TextInputValue }) }
   value={ this.state.image_uri }
   underlineColorAndroid='transparent'

   style={styles.TextInputStyleClass}
 />

<TouchableOpacity activeOpacity = { .4 } style={styles.TouchableOpacityStyle} onPress={() => this.saveUserdata()} >

  <Text style={styles.TextStyle}> INSERT PRODUCT TO SERVER </Text>

</TouchableOpacity>

<TouchableOpacity activeOpacity = { .4 } style={styles.TouchableOpacityStyle}  onPress={() => Actions.black()}  >

  <Text style={styles.TextStyle}> SHOW ALL INSERTED PRODUCTS RECORDS</Text>

</TouchableOpacity>
</KeyboardAvoidingView>
        </ScrollView>

    </View>
  );
  }

  signup() {
    if(this.state.product===""||this.state.price===""||this.state.unit===""||this.state.section==="") {
      this.setState({hasError: true, errorText: 'Please fill all fields !'});
      return;
    }
    this.saveUserdata();
  }

  saveUserdata() {
    const newDocumentData = this.ref.collection('products').doc().id;
    this.setState({
      loading: true,
    });
    const userId = firebase.auth().currentUser.uid;
    this.ref.collection('products').doc(newDocumentData).set({
      store_id: firebase.auth().currentUser.uid,
      pr_name: this.state.product,
      pr_id: newDocumentData,
      pr_price: this.state.price,
      pr_unit: this.state.unit,
      pr_store_name: firebase.auth().currentUser.email, //change into name of store.
      pr_section : this.state.section,
      pr_image: this .state.image,
      prod_status: 'active',
    }).then((docRef) => {
      this.setState({
        image: '',
        section: '',
        unit: '',
        price: '',
        product: '',
        status: '',
        isloading: false,
      });
      Actions.gold();
    })
  }



}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#ffdf00',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
    color: '#ffffff',
  },

    MainContainer :{

      alignItems: 'center',
      flex:1,
      paddingTop: 30,
      backgroundColor: '#fff'

    },

    MainContainer_For_Show_StudentList_Activity :{

      flex:1,
      paddingTop: (Platform.OS == 'ios') ? 20 : 0,
      marginLeft: 5,
      marginRight: 5

      },

    TextInputStyleClass: {

    textAlign: 'center',
    width: '90%',
    marginBottom: 7,
    height: 40,
    borderWidth: 1,
    borderColor: '#FF5722',
    borderRadius: 5 ,

    },

    TouchableOpacityStyle: {

      paddingTop:10,
      paddingBottom:10,
      borderRadius:5,
      marginBottom:7,
      width: '90%',
      backgroundColor: '#00BCD4'

    },

    TextStyle:{
      color:'#fff',
      textAlign:'center',
    },

    rowViewContainer: {
      fontSize: 20,
      paddingRight: 10,
      paddingTop: 10,
      paddingBottom: 10,
    },
    imageContainer: {
      backgroundColor: '#fe5b29',
      height: Dimensions.get('window').height
    },
    backgroundImage: {
      flex: 1,
      resizeMode: 'cover',
    },
    uploadContainer: {
      backgroundColor: '#f6f5f8',
      borderTopLeftRadius: 45,
      borderTopRightRadius: 45,
      position: 'absolute',
      bottom: 0,
      width: Dimensions.get('window').width,
      height: 200,
    },
    uploadContainerTitle: {
      alignSelf: 'center',
      fontSize: 25,
      margin: 20,
      fontFamily: 'Roboto'
    },
    uploadButton: {
      borderRadius: 16,
      alignSelf: 'center',
      shadowColor: "#000",
      shadowOffset: {
        width: 7,
        height: 5,
      },
      shadowOpacity: 1.58,
      shadowRadius: 9,
      elevation: 4,
      margin: 10,
      padding: 10,
      backgroundColor: '#fe5b29',
      width: Dimensions.get('window').width - 60,
      alignItems: 'center'
    },
    uploadButtonText: {
      color: '#f6f5f8',
      fontSize: 20,
      fontFamily: 'Roboto'
    }

});

这是我的 firebase.js 代码

import * as firebase from 'firebase';
import firestore from 'firebase/firestore'

const settings = {timestampsInSnapshots: true};

const config = {
    apiKey: "<apikey_value>",
    authDomain: "<value>",
    databaseURL: "<value>",
    projectId: "<value>",
    storageBucket: "<value>",
    messagingSenderId: "<value>",
    appId: "<value>",
    measurementId: "<value>"
};
firebase.initializeApp(config);


export default firebase;

【问题讨论】:

    标签: javascript firebase react-native google-cloud-firestore


    【解决方案1】:

    我只是换了

    // Prepare Blob support 
    const Blob = RNFetchBlob.polyfill.Blob
    const fs = RNFetchBlob.fs
    window.XMLHttpRequest = RNFetchBlob.polyfill.XMLHttpRequest
    window.Blob = Blob
    

    进入

    // Prepare Blob support
    window.XMLHttpRequest = RNFetchBlob.polyfill.XMLHttpRequest;
    const Blob = RNFetchBlob.polyfill.Blob;
    const fs = RNFetchBlob.fs;
    window.Blob = Blob;
    
    const originalBlob = window.Blob;
    window.XMLHttpRequest = tempWindowXMLHttpRequest;
    

    但另一个问题显示。即使我已经向 androidmanifest.xml 添加了权限,也没有授予相机权限。

    这里是代码

    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.sampling">
    
        <uses-permission android:name="android.permission.INTERNET" />
    <!-- < Only if you're using GCM or localNotificationSchedule() > -->
        <uses-permission android:name="android.permission.WAKE_LOCK" />
        <permission
            android:name="com.sampling.permission.C2D_MESSAGE"
            android:protectionLevel="signature" />
        <uses-permission android:name="com.sampling.permission.C2D_MESSAGE" />
        <!-- < Only if you're using GCM or localNotificationSchedule() > -->
    
        <uses-permission android:name="android.permission.VIBRATE" />
        <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
          <uses-permission android:name="android.permission.CAMERA"/>
       <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    
        <application
          android:name=".MainApplication"
          android:label="@string/app_name"
          android:icon="@mipmap/ic_launcher"
          android:roundIcon="@mipmap/ic_launcher_round"
          android:allowBackup="false"
          android:theme="@style/AppTheme">
          <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
            android:windowSoftInputMode="adjustResize">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
          </activity>
    
                                <meta-data  android:name="com.dieam.reactnativepushnotification.notification_channel_name"
                                        android:value="YOUR NOTIFICATION CHANNEL NAME"/>
                                <meta-data  android:name="com.dieam.reactnativepushnotification.notification_channel_description"
                                            android:value="YOUR NOTIFICATION CHANNEL DESCRIPTION"/>
                                <!-- Change the resource name to your App's accent color - or any other color you want -->
                                <meta-data  android:name="com.dieam.reactnativepushnotification.notification_color"
                                            android:resource="@android:color/white"/>
    
                                <!-- < Only if you're using GCM or localNotificationSchedule() > -->
                                <receiver
                                    android:name="com.google.android.gms.gcm.GcmReceiver"
                                    android:exported="true"
                                    android:permission="com.google.android.c2dm.permission.SEND" >
                                    <intent-filter>
                                        <action android:name="com.google.android.c2dm.intent.RECEIVE" />
                                        <category android:name="com.sampling" />
                                    </intent-filter>
                                </receiver>
                                <!-- < Only if you're using GCM or localNotificationSchedule() > -->
    
                                <receiver android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationPublisher" />
                                <receiver android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationBootEventReceiver">
                                    <intent-filter>
                                        <action android:name="android.intent.action.BOOT_COMPLETED" />
                                    </intent-filter>
                                </receiver>
                                <service android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationRegistrationService"/>
    
                                <!-- < Only if you're using GCM or localNotificationSchedule() > -->
                                <service
                                    android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationListenerServiceGcm"
                                    android:exported="false" >
                                    <intent-filter>
                                        <action android:name="com.google.android.c2dm.intent.RECEIVE" />
                                    </intent-filter>
                                </service>
                                <!-- </ Only if you're using GCM or localNotificationSchedule() > -->
    
                                <!-- < Else > -->
                                <service
                                    android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationListenerService"
                                    android:exported="false" >
                                    <intent-filter>
                                        <action android:name="com.google.firebase.MESSAGING_EVENT" />
                                    </intent-filter>
                                </service>
    
          <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
        </application>
    
    </manifest>
    

    【讨论】:

      猜你喜欢
      • 2018-11-10
      • 2020-08-09
      • 2022-01-23
      • 2020-05-27
      • 2023-03-22
      • 1970-01-01
      • 2018-10-22
      • 2020-03-13
      • 2018-12-30
      相关资源
      最近更新 更多