React Native Cli集成geofirestore遇TypeError问题求助
解决GeoFirestore的TypeError问题
错误原因
出现GeoFirestore.collection is not a function的核心问题:
- 直接调用
GeoFirestore类的collection方法,但该方法属于实例对象而非类本身 - Firebase v9模块化版本中,
GeoPoint的调用方式错误 - 自定义变量
query与Firebase导入的query重名,引发冲突
修复步骤及代码修改
1. 调整实现文件的导入逻辑
删除实现文件中单独导入的GeoFirestore,改为导入配置文件中已实例化好的geofirestore对象;同时导入Firebase的GeoPoint。
2. 修正集合获取与地理查询代码
使用实例化的geofirestore调用collection,修正GeoPoint创建方式,避免变量名冲突。
修改后的实现文件代码:
import { useNavigation } from "@react-navigation/native"; import { useEffect, useState } from "react"; import GetLocation from 'react-native-get-location' import { collection, onSnapshot, orderBy, query, where, getDocs, GeoPoint } from "firebase/firestore"; // 新增GeoPoint导入 import { db, geofirestore } from "../../utils/keys" // 导入配置好的geofirestore实例 import { getAuth } from "firebase/auth"; const obtenerRegistrosCercanos = async () => { // 使用实例化的geofirestore获取集合 const eventosCollection = geofirestore.collection('eventos'); // 用导入的GeoPoint创建地理坐标 const center = new GeoPoint(19.325471, -99.656188); const radius = 10; // 避免变量名冲突,将query改为geoQuery const geoQuery = eventosCollection.near({ center, radius, }); geoQuery.get().then((snapshot) => { snapshot.docs.forEach((doc) => { const data = doc.data(); console.log(data); }); }); };
3. 确认配置文件的正确性
你的配置文件已正确实例化GeoFirestore,无需修改,保持如下即可:
import { initializeApp } from 'firebase/app'; import { getAuth } from 'firebase/auth'; import { getFirestore } from 'firebase/firestore'; import { GeoFirestore } from 'geofirestore'; const firebaseConfig = { // 你的配置信息 }; const app = initializeApp(firebaseConfig); const authentication = getAuth(app); const db = getFirestore(app); const geofirestore = new GeoFirestore(db); export { app, authentication, db, geofirestore };
额外注意事项
- 确保
eventos集合中的文档包含地理坐标字段(默认是geopoint,若自定义字段名,需在near方法中指定field参数) - 地理查询需要Firestore索引支持,若运行后出现索引错误,按照控制台提示创建对应地理索引
内容的提问来源于stack exchange,提问作者erick valle
相关产品推荐
相关产品推荐

