如何在React Native应用中从Firebase实时数据库获取数据
如何从Firebase实时数据库获取数据(适配原Firestore代码)
你的实时数据库结构如下:
你当前使用Firestore的代码如下:
import React, { useEffect, useState, useContext, } from 'react'; import { View, Text, Image, StyleSheet, ScrollView, SafeAreaView, ActivityIndicator, FlatList, } from 'react-native'; import {firebase} from '../config'; export default function App() { const [users, setUsers] = useState([]); const todoRef = firebase.firestore().collection('testing'); useEffect(() => { todoRef.onSnapshot( querySnapshot => { const users = [] querySnapshot.forEach((doc) => { const { one, two, three, four } = doc.data() users.push({ id: doc.id, one, two, three, four }) }) setUsers(users) } ) }, []) return ( <View style={{ backgroundColor: theme.viewOne, }}> {isLoading ? <ActivityIndicator /> : ( <FlatList ListHeaderComponent={ <Image source={require('./AllImage/qq2.jpg')} style={{ width: "auto", height: 150, resizeMode: "cover", }} /> } data={data} keyExtractor={({ id }, index) => id} renderItem={({ item }) => ( <View style={styles.container}> <View style={styles.item}> <Text style={styles.mainText}>{item.one}</Text> </View> <View style={styles.item}> <Text style={styles.mainText}>{item.two}</Text> </View> </View> )} /> )} </View> ); };
注:当前代码使用的是Firestore,需要适配为从Firebase实时数据库获取数据的实现方式。
适配后的实时数据库获取代码
核心修改点
- 替换Firestore引用为实时数据库引用:
firebase.database().ref('testing') - 使用实时数据库的
on('value')监听数据变化,替代Firestore的onSnapshot - 遍历实时数据库子节点,将数据转换为数组格式
完整适配代码
import React, { useEffect, useState } from 'react'; import { View, Text, Image, ActivityIndicator, FlatList, } from 'react-native'; import { firebase } from '../config'; export default function App() { // 补充原代码未定义的状态变量 const [users, setUsers] = useState([]); const [isLoading, setIsLoading] = useState(true); // 实时数据库引用,指向'testing'节点 const todoRef = firebase.database().ref('testing'); useEffect(() => { // 监听实时数据库数据变化 const unsubscribe = todoRef.on('value', (snapshot) => { const usersData = []; // 遍历所有子节点,提取数据 snapshot.forEach((childSnapshot) => { const childData = childSnapshot.val(); usersData.push({ id: childSnapshot.key, // 实时数据库用key作为唯一标识 one: childData.one, two: childData.two, three: childData.three, four: childData.four }); }); setUsers(usersData); setIsLoading(false); }); // 组件卸载时取消监听,避免内存泄漏 return () => unsubscribe(); }, []); return ( <View style={{ backgroundColor: '#fff' }}> {/* 替换原未定义的theme.viewOne,可根据项目调整 */} {isLoading ? <ActivityIndicator size="large" /> : ( <FlatList ListHeaderComponent={ <Image source={require('./AllImage/qq2.jpg')} style={{ width: "auto", height: 150, resizeMode: "cover", }} /> } data={users} // 修正原代码错误的data变量 keyExtractor={(item) => item.id} renderItem={({ item }) => ( <View style={{ padding: 16, borderBottomWidth: 1, borderBottomColor: '#eee' }}> <View style={{ marginBottom: 8 }}> <Text style={{ fontSize: 16, fontWeight: 'bold' }}>{item.one}</Text> </View> <View> <Text style={{ fontSize: 14 }}>{item.two}</Text> </View> </View> )} /> )} </View> ); };
额外注意事项
- 确保Firebase配置文件已正确初始化实时数据库(通常在
../config.js中已包含,若缺失需补充) - 开发阶段可临时设置实时数据库权限规则为
{ "rules": { ".read": true, ".write": true } },生产环境需严格配置权限 - 原代码中
theme、data等未定义变量已做修正,可根据实际项目调整样式和变量名
内容的提问来源于stack exchange,提问作者Rahul Aadam
相关产品推荐
相关产品推荐

