如何使用React Native将数据保存到Firebase?

时间:2020-05-30 16:41:37

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

我使用https://github.com/expo-community/expo-firebase-starter作为入门模板来使用Firebase构建React Native应用。

我正在Home.js中处理以下文件,并想将数据保存到Firebase,但出现错误。错误。

firebase.database is not a function. (In 'firebase.database(reflection)', 'firebase.database' is undefined)

这是我正在使用的代码。有人写反射时,我试图将反射文本与用户ID一起保存。

import React, {useEffect, useState } from "react";
import { StyleSheet, Text, View } from "react-native";
import { Container, Content, Header, Form, Input, Item, Label } from 'native-base';
import { Button } from "react-native-elements";
import { withFirebaseHOC } from "../config/Firebase";
import * as firebase from 'firebase';
import "firebase/database";

function Home({ navigation, firebase }) {

  const [reflection, setReflection] = useState('');
  const[member, setMember] = useState('');

  useEffect(() => {
    try {

      firebase.checkUserAuth(user => {
        if (user) {
          // if the user has previously logged in

          setMember(user);
          console.log(member);

        } else {
          // if the user has previously logged out from the app
          navigation.navigate("Auth");
        }
      });
    } catch (error) {
      console.log(error);
    }
  }, []);

  async function postReflection() {

    try {
      await console.log(reflection);
      await console.log(member.email);

    firebase.database(reflection).ref('Posts/').set({
        reflection,
    }).then((data)=>{
        //success callback
        console.log('data ' , data)
    }).catch((error)=>{
        //error callback
        console.log('error ' , error)
    })

    } catch (error) {
      console.log(error);
    }


  }

  async function handleSignout() {
    try {
      await firebase.signOut();
      navigation.navigate("Auth");
    } catch (error) {
      console.log(error);
    }
  }

  return (
    <Container style={styles.container}>

          <Form>
            <Item floatingLabel>
              <Label>Reflection</Label>
              <Input 
                autoCapitalize='none'
                autoCorrect={false}
                onChangeText={text => setReflection(text)}
              />
            </Item>

              <Button style = {{ marginTop: 10, marginHorizontal:30 }}
                title="Share"
                rounded
                onPress= {postReflection}
                >
              </Button>
              </Form>


      <Button
        title="Signout"
        onPress={handleSignout}
        titleStyle={{
          color: "#F57C00"
        }}
        type="clear"
      />
    </Container>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#fff",
    // justifyContent: "center"
  }
});

export default withFirebaseHOC(Home);

2 个答案:

答案 0 :(得分:0)

import * as firebase from 'firebase';

之后添加以下内容
import "firebase/database";

每个Firebase产品都有必须添加的单独的API,如documentation中所述。

答案 1 :(得分:0)

您的/config/Firebase/firebase.js没有database属性。看一下Firebase对象是如何导出的。

// inside /config/Firebase/firebase.js

import "firebase/database"; // add this

// Initialize Firebase
firebase.initializeApp(firebaseConfig);

const Firebase = {
  // add this
  database: () => {
    return firebase.database()
  }
};

export default Firebase;

已阅读此步骤。您不仅可以导入firebase库的一部分,还需要将其实际分配给变量并导出以使用它。 https://firebase.google.com/docs/web/setup#namespace