可能的未处理的承诺拒绝(id:0):TypeError:网络请求失败

问题描述 投票:1回答:1

我想在react native中将包含文本和图像的帖子发送到Firebase数据库。

问题是我收到此错误:Error Message在PostScreen中,显示发布帖子的按钮。在Fire.js中,它会被处理并发送到数据库。

我希望有人可以帮助我解决该错误。

PostScreen.js

import React, { Component } from 'react';
import {
  View, 
  Text, 
  StyleSheet, 
  Alert, 
  FlatList, 
  ScrollView, 
  SafeAreaView, 
  TouchableOpacity, 
  Image, 
  TextInput, 
  Button, 
  PermissionsAndroid, 
  NativeModules
} from 'react-native';
import {Ionicons} from '@expo/vector-icons';
import Constants from 'expo-constants';
import * as Permissions from 'expo-permissions';
import Fire from '../src/Fire';
import ImagePicker from 'react-native-image-crop-picker';

const firebase = require("firebase");
require("firebase/firestore");

export default class PostScreen extends Component {
    
    state = {
        text: "",
        image: null,
    };

    handlePost = () => {
      Fire.shared
      .addPost({ text: this.state.text.trim(), localUri: this.state.image })
      .then(ref => {
        this.setState({ text: "", image: null });
        this.props.navigation.goBack();
      })
      .catch(error => {
        alert(error.message);
      });      
    };


    pickSingle = () => {
      ImagePicker.openPicker({
        width: 500,
        height: 500,
        cropping: true
      }).then(image => {
        console.log('received image', image);
        this.setState({
          image: {uri: image.path, width: image.width, height: image.height, mime: image.mime},
        });
      }).catch(e => {
        console.log(e);
        Alert.alert(e.message ? e.message : e);
      });
    }

    renderImage(image) {
      return <Image style={{width: 300, height: 300, resizeMode: 'contain'}} source={image} />
    }
  
    renderAsset(image) {
      return this.renderImage(image);
    }

    componentDidMount() {
        this.requestCameraRollPermission();
    }

    getPhotoPermission = async () => {
        const { status } = await Permissions.getAsync(Permissions.READ_EXTERNAL_STORAGE);
        if (status !== 'granted') {
          alert('We need access to your camera rool');
        }
      };

    requestCameraRollPermission = async () => {
        try {
          const granted = await PermissionsAndroid.request(
            PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE);
          if (granted === PermissionsAndroid.RESULTS.GRANTED) {
            return null;
          } else {
            return null;
          }
        } catch (err) {
          return null;
        }
      };

    requestCameraPermission = async () => {
        try {
          const granted = await PermissionsAndroid.request(
            PermissionsAndroid.PERMISSIONS.CAMERA);
          if (granted === PermissionsAndroid.RESULTS.GRANTED) {
            return null;
          } else {
            return null;
          }
        } catch (err) {
          return null;
        }
      };    

    render() {
        return (
            <SafeAreaView style={styles.container}>
                <View style={styles.header}>
                    <TouchableOpacity onPress={() => this.props.navigation.goBack()}>
                        <Ionicons name="md-arrow-back" size={24} color="#D8D9D8"></Ionicons>
                    </TouchableOpacity>
                    <TouchableOpacity onPress={this.handlePost}>
                        <Text style={{ fontSize: 15 ,fontWeight: 'bold', color: '#1d6fa4' }}>Post</Text>
                    </TouchableOpacity>
                </View>

            <View style={styles.inputContainer}>
                <Image style={styles.avatar}></Image>
                <TextInput
                    autoFocus={true}
                    multiline={true}
                    numberOfLines={4}
                    style={{ flex: 1 }}
                    placeholder='Want to share something?'
                    onChangeText={text => this.setState({ text })}
                    value={this.state.text}
                ></TextInput>
            </View>

            <View style={styles.icons}>
                <TouchableOpacity style={styles.photo}>
                    <Ionicons name="md-photos" size={32} color='#D8D9DB' onPress={this.pickSingle} ></Ionicons>
                </TouchableOpacity>
                <TouchableOpacity style={styles.camera}>
                    <Ionicons name="md-camera" size={32} color='#D8D9DB' ></Ionicons>
                </TouchableOpacity>
            </View>

                <ScrollView style={{ marginHorizontal: 25, marginTop: 25, height: 150, }}>
                  {this.state.image ? this.renderAsset(this.state.image) : null}
                  {this.state.images ? this.state.images.map(i => <View key={i.uri} style={{ alignItems: 'center' }}>{this.renderAsset(i)}</View>) : null}
                </ScrollView>
            </SafeAreaView>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
    },
    header: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        paddingHorizontal: 32,
        paddingVertical: 12,
        borderBottomWidth: 1,
        borderBottomColor: '#D8D9D8'
    },
    inputContainer: {
        margin: 32,
        flexDirection: "row",
        borderWidth: 0.5,
        borderColor: '#D8D9D8'
    },
    avatar: {
        width: 48,
        height: 48,
        borderRadius: 24,
        marginRight: 16
    },
    icons: {
        flexDirection: 'row',
        justifyContent: 'flex-end'
    },
    photo: {
      marginRight: 20
    },
    camera: {
      marginRight: 33
    },
    imgContainer: {
      marginVertical: 20
    },
    button: {
      backgroundColor: 'blue',
      marginBottom: 10,
    },
    text: {
        color: 'white',
        fontSize: 20,
        textAlign: 'center'
    },
    title: {
        fontWeight: 'bold',
        fontSize: 22
    },
    safeArea: {
        marginTop: 20
    },
    dateContainer: {
        flexDirection: 'row',
    },
    imgView: {
        width: '50%',
        marginVertical: 10,

    }
});

Fire.js

import firebase from 'firebase';


var firebaseConfig = {
    apiKey: "AIzaSyB1Z4eYKBoQVxREriGRi9neur5pVbIr2d8",
    authDomain: "caring-1.firebaseapp.com",
    databaseURL: "https://caring-1.firebaseio.com",
    projectId: "caring-1",
    storageBucket: "caring-1.appspot.com",
    messagingSenderId: "369253724134",
    appId: "1:369253724134:web:49a7597841cdd55970f027"
  };

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

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

        return new Promise((res, rej) => {
            this.firestore
                .collection("posts")
                .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;
firebase react-native react-native-android react-native-ios
1个回答
0
投票

您必须在函数uploadPhotoAsync中对此进行更改“ stated_changed”到firebase.storage.TaskEvent.STATE_CHANGED。

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(
    firebase.storage.TaskEvent.STATE_CHANGED,
    (snapshot) => {},
    (err) => {
      rej(err);
    },
    async () => {
      const url = await upload.snapshot.ref.getDownloadURL();
      res(url);
    }
  );
});

这对我有用

© www.soinside.com 2019 - 2024. All rights reserved.