【问题标题】:React Native: Possible unhandled promise rejection (id: 0) TypeError: Network request failedReact Native:可能未处理的承诺拒绝(id:0)TypeError:网络请求失败
【发布时间】:2020-01-07 16:36:07
【问题描述】:

我收到以下错误:可能未处理的承诺拒绝 (id:0):网络请求失败。 enter image description here

我正在尝试用 firebase 中的文字和图片来传达评论。在 ReviewScreen.js 中实现数据的显示和接受,在 Fire.js 中处理和发送。我认为在 Fire.js 的某个地方存在错误,但我不知道问题出在哪里

ReviewsScreen.js

import React, { Component } from 'react';
import {
  StyleSheet,
  View,
  TouchableOpacity,
  Text,
  SafeAreaView,
  Image,
  TextInput,
 SafeAreaViewBase
} from 'react-native';
import Icon from 'react-native-vector-icons/Ionicons'
import {h, w} from '../../constants'
import Fire from '../../Fire'
import ImagePicker from 'react-native-image-picker';


const options = {
  title: 'Select photo',
};

export default class ReviewsScreen extends Component {
  state = {
    text: '',
    image: null
  }

pickImage = () => 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 {
  // You can also display the image using data:
  // const source = { uri: 'data:image/jpeg;base64,' + response.data };

  this.setState({
    image: response.uri
  });
}
  });

  handleReview = () => {
Fire.shared.addReview({text: this.state.text.trim(), localUrl: this.state.image}).then(ref => {
  this.setState({text: '', image: null})
  this.props.navigation.goBack()
}).catch(error => {
  alert(error)
})
  }

  render() {
return (
  <SafeAreaView style={styles.container}>
    <View style={styles.header}>
      <TouchableOpacity onPress={() => this.props.navigation.goBack()}>
        <Icon name='md-arrow-back' size={24} color='blue'/>
      </TouchableOpacity>
      <TouchableOpacity onPress={this.handleReview}>
        <Text style={{fontWeight: '500'}}>Добавить</Text>
      </TouchableOpacity>
    </View>

    <View style={styles.inputContainer}>
      <Image source={require('./img/avatar.jpg')} style={styles.avatar}/>
      <TextInput
        autoFocus={true}
        multiline={true}
        numberOfLines={1}
        style={{flex: 1}}
        placeholder='Нам важно ваше мнение!'
        onChangeText={text => this.setState({ text })}
        value={this.state.text}
      >
      </TextInput>
    </View>

    <TouchableOpacity style={styles.photo} 
      onPress={this.pickImage}>
      <Icon name='md-camera' size={32} color="#D8D9D8"></Icon>
    </TouchableOpacity>

    <View syle={{marginHorizontal: 32, marginTop: 32, height: 150}}>
      <Image source={{uri: this.state.image}} style={{ marginTop: 32, alignSelf: 'center', width: '50%', height: '50%'}} />
    </View>
  </SafeAreaView>
    )
  }
}

Fire.js

import firebaseConfig from './config'
import firebase from 'firebase'

class Fire {
  constructor() {
      firebase.initializeApp(firebaseConfig);
  }

addReview = async ({ text, localUri }) => {
  const remoteUri = await this.uploadPhotoAsync(localUri);

  return new Promise((res, rej) => {
      this.firestore
          .collection("reviews")
          .add({
              text,
              uid: this.uid,
              timestamp: this.timestamp,
              image: remoteUri
          })
          .then(ref => {
              res(ref);
          })
          .catch(error => {
              rej(error)
          });
  });
  };

uploadPhotoAsync = async uri => {
  const path = `photos/${this.uid}/${Date.now()}.jpg`;

  return new Promise(async (res, rej) => {
      const response = await fetch(uri);
      const file = await response.blob();

      let upload = firebase
          .storage()
          .ref(path)
          .put(file);

      upload.on(
          "state_changed",
          snapshot => {},
          err => {
              rej(err);
          },
          async () => {
              const url = await upload.snapshot.ref.getDownloadURL();
              res(url);
          }
      );
  });
};

get firestore() {
   return firebase.firestore();
}

get uid() {
    return (firebase.auth().currentUser || {}).uid;
}

get timestamp() {
    return Date.now();
}
}

Fire.shared = new Fire();
export default Fire;

【问题讨论】:

  • 任何时候你得到未处理的承诺拒绝错误,这意味着你在代码中的某处处理错误时遇到了问题。尝试将您的函数包装在 async-await 块中的 try-catch 块中。
  • @Uladzislau Rusy,你找到问题了吗?
  • 还有答案吗?卡在同一个地方。 @ula

标签: javascript reactjs firebase react-native firebase-realtime-database


【解决方案1】:

你写的是“localUrl”而不是“localUri”: Fire.shared.addReview({text: this.state.text.trim(), localUrl: this.state.image}).then(ref =&gt; {

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-12
    • 2021-06-25
    • 2020-10-28
    • 1970-01-01
    • 2017-12-20
    • 2018-02-09
    • 1970-01-01
    • 2020-06-30
    相关资源
    最近更新 更多