firebase - 无法将数据添加到 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' 未定义)
我究竟做错了什么?
谢谢
解决方案
您没有显示导出为firestore
from 的内容./config/firebase
,但它一定是您所期望的。
根据Firebase 文档,您希望按照以下方式做一些事情:
var db = firebase.firestore()
db.collection("users").doc //etc
因此,在这种情况下,您希望db
像firestore
在您的config/firebase/
请注意,这是针对 Web API 的第 8 版,我假设您根据您的代码检查使用它firebase.apps.length
。如果您使用的是版本 9,则需要更新新 API 的代码。
推荐阅读
- c - 提示用户重新输入号码
- html - 通过正则表达式查找特定的url
- c# - NetTopologySuite 以何种单位返回距离,如何将其转换为英里/公里?
- javascript - 什么 Javascript if/else 语句可以将放大的图像返回到其默认大小?
- performance - 使用 Azure DevOps 版本无法在 azure CI 管道中运行 vsts2017 Web 测试
- php - LUMEN:如何修复 SQLSTATE [42000]:语法错误或访问冲突:laravel 流明上的 1071
- mongoose - 将虚拟属性值传递给 Mongoose `pre-save` 钩子
- php - 富文本编辑器不将某些输入从 TextArea 保存到 MySQL
- excel - 如何使用 POI 4.0.1 Java 在条形图中添加垂直线
- javascript - 为什么我的数组中的项目没有显示在单独的行上?