【发布时间】:2020-11-22 15:34:17
【问题描述】:
我正在从 firebase 获取数据,但能够在模拟器上获取数据我尝试使用 consloe 工作正常
const Getdata = async () => {
await firebase.database().ref(`/orders/${user1.uid}`)
.on("child_added", (snapshot, key) => {
if(snapshot.key) {
console.log('key',snapshot.key);
let grabbedData = snapshot.val().orders;
grabbedData.map((order, i) => {
console.log('order',order.id);
console.log('order',order.avatar);
console.log('order',order.name);
console.log('order',order.price);
console.log('----------------');
});
}
});
}
Getdata();
将以上代码修改为以下代码后,屏幕上没有任何显示
const Getdata = () => {
let data = firebase.database().ref(`/orders/${user1.uid}`)
.on("child_added", (snapshot, key) => {
// something is wrong with this below statememnt I think
return (
<Card>
<Text>{snapshot.key}</Text>
{
snapshot.val().orders.map((order, i) => {
return (
<TouchableOpacity key={i} onPress={() => {
}}>
<Card>
<View style={styles.user}>
<Image
style={styles.image}
resizeMode="cover"
source={{ uri: order.avatar }}
/>
<View style={{flexDirection:'column', flex: 1}}>
<Text style={styles.name} h4>{order.name}</Text>
<Card.Divider style={{ marginTop: 25}}/>
<View style={{flexDirection:'row', flex: 1,justifyContent: 'space-between'}}>
<Text style={styles.price}>{order.price}</Text>
</View>
</View>
</View>
</Card>
</TouchableOpacity>
);
})
}
</Card>
)
})
return data;
}
and then <Getdata/>
【问题讨论】:
-
on()既不返回承诺,也不返回数据。所以,你在这两种情况下使用它的方式都是不正确的。您的意思是改用once(),它会返回一个带有数据库数据的承诺吗? -
但是使用一次只能获取一次数据并希望它是实时的
-
您将不得不选择是希望函数返回数据还是实时监听。你不能同时使用同一个 API。
标签: javascript firebase react-native firebase-realtime-database