首页 > 解决方案 > 无法将数据添加到 Firestore 集合?

问题描述

我是 React Native/Expo 的新手。我正在尝试将 Firebase Firestore 与我的应用程序集成,以便我可以保留一些数据。

firebase.js在一个名为的文件夹中创建了一个文件config

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

const firebaseConfig = {
  // All the relevant firebase config data is here, removed for this post
};

// Initialize Firebase
if (!firebase.apps.length) {
  const app = firebase.initializeApp(firebaseConfig).firestore();
} else {
  const app = firebase.app().firestore();
}

在我的App.js中,我试图将设备的纬度和经度保存到 Firestore:

import React, { useState, useEffect } from 'react';
import { Platform, Text, View, StyleSheet } from 'react-native';

import firebase from "./config/firebase";

import * as Location from 'expo-location';

export default function App() {
  const [location, setLocation] = useState(null);
  const [errorMsg, setErrorMsg] = useState(null);

  const add = (x, y) => {
    if (x === null || x === "" || y === null || y === "") {
      return false;
    }

    firebase.collection("users")
      .doc(1)
      .set({
        x: x,
        y: y
      });
  };

  useEffect(() => {
    (async () => {
      let { status } = await Location.requestForegroundPermissionsAsync();
      if (status !== 'granted') {
        setErrorMsg('Permission to access location was denied');
        return;
      }

      let location = await Location.getCurrentPositionAsync({});
      setLocation(location);
    })();
  }, []);

  let text = 'Waiting..';
  if (errorMsg) {
    text = errorMsg;
  } else if (location) {
    text = JSON.stringify(location);

    add(location.coords.latitude, location.coords.longitude);
  }

  return (
    <View style={styles.container}>
      <Text style={styles.paragraph}>{text}</Text>
    </View>
  );
}

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

相当简单的东西。

但是,当我运行它时,我收到一个错误:

组件异常

_firebase.default.collection 不是函数。(在 '_firebase.default.collection("users")` 中,'_firebase.default.collection' 未定义)

我究竟做错了什么?

谢谢

标签: firebasereact-nativegoogle-cloud-firestoreexpo

解决方案


您没有显示导出为firestorefrom 的内容./config/firebase,但它一定是您所期望的。

根据Firebase 文档,您希望按照以下方式做一些事情:

var db = firebase.firestore()
db.collection("users").doc //etc

因此,在这种情况下,您希望dbfirestore在您的config/firebase/

请注意,这是针对 Web API 的第 8 版,我假设您根据您的代码检查使用它firebase.apps.length。如果您使用的是版本 9,则需要更新新 API 的代码。


推荐阅读