【问题标题】:Can't add data to Firestore collection?无法将数据添加到 Firestore 集合?
【发布时间】:2021-11-30 12:49:07
【问题描述】:

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

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

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' 未定义)

我做错了什么?

谢谢

【问题讨论】:

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


    【解决方案1】:

    顺便说一句,您正在导入库作为 documentation 中的示例。显然,您使用的是 SDK 版本 9(模块化),因此管理数据的方式有所不同。大家可以比较一下here的区别。

    documentation一样,版本8如下:

    // Add a new document in collection "cities"
    db.collection("cities").doc("LA").set({
        name: "Los Angeles",
        state: "CA",
        country: "USA"
    })
    

    在版本 9 中,应该这样做:

    import { doc, setDoc } from "firebase/firestore"; 
    
    // Add a new document in collection "cities"
    await setDoc(doc(db, "cities", "LA"), {
      name: "Los Angeles",
      state: "CA",
      country: "USA"
    });
    

    您还应该check the firestore version you are runningset up your environment accordingly

    【讨论】:

      【解决方案2】:
      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();
      export default app;
      } else {
        const app = firebase.app().firestore();
      export default app;
      }
      

      在使用 import firebase from "./config/firebase" 之前;您需要导出默认值;这样导入的变量“firebase”将是“firebase.app().firestore();”或“firebase.initializeApp(firebaseConfig).firestore()”

      然后你可以 firebase.collection("users") .doc(1) .set({ x: x, y: y });因为变量firebase实际上是firestore

      【讨论】:

      • 您能否添加几句话来解释您的代码如何回答 OP 的问题?
      • 在你使用 import firebase from "./config/firebase" 之前;您需要导出默认值;这样导入的变量“firebase”将是“firebase.app().firestore();”或“firebase.initializeApp(firebaseConfig).firestore()”
      • 然后你可以 firebase.collection("users") .doc(1) .set({ x: x, y: y });因为变量 firebase 实际上是 firestore
      • edit您的帖子而不是评论。
      【解决方案3】:

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

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

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

      因此,在这种情况下,您希望将db 导出为firestore 在您的config/firebase/

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

      【讨论】:

        猜你喜欢
        • 2020-09-12
        • 2022-06-11
        • 1970-01-01
        • 2022-01-05
        • 1970-01-01
        • 2021-12-21
        • 2021-02-16
        • 2023-03-24
        • 1970-01-01
        相关资源
        最近更新 更多