从React Native中的Firebase子对象检索数据

时间:2017-12-11 20:07:17

标签: react-native

我正在尝试从反应Native Application中的firebase获取数据。

以下是我的数据库:enter image description here

https://ibb.co/cEVBeb

QWA17SaADRdgluvVnYrXJK1AvI22
-L-uNMmDRnKTkk55KbMz
allowGPS: true  
notificationSound:  true  
phone:  "345345345345345" 
pushNotification:  true 
shareData:  true  
showAlerts:  true 

下面是我尝试过的代码,但它们无法正常工作。 有人可以指导我如何获得嵌套值。

firebase.database().ref(`/users/${currentUser.uid}`)
.once('value').then((snapshot) => {
const username = (snapshot.val() && snapshot.val().username) || 'Anonymous';
console.log(snapshot.val().username);
console.log(snapshot.val());
console.log(snapshot.val('username'));
console.log(snapshot.child('phone').val());

2 个答案:

答案 0 :(得分:2)

如果你的火力架结构

,你还有一个巢
QWA17SaADRdgluvVnYrXJK1AvI22
    -L-uNMmDRnKTkk55KbMz //HERE

因此使用snapshot.val()不会访问您的子组件。您只应在创建用户时创建其中一个代码,并将密钥(QWA17Sa ...)指定为其user_id。这个其他代码是不必要的。

要执行此操作,请在为firebase创建用户时使用.set方法,类似于以下内容。这应该避免在firebase结构中创建这个单独的不需要的节点。

    const userPath = `/users/${currentUser}`;

    // Save the text and a url to the saved audio file to firebase.
    firebase.database().ref(userPath).set({
      username: foo
      stuff: foo
    });

答案 1 :(得分:0)

可以试试这段代码。对我来说它有效

firebase.database().ref('/users/' + firebase.auth().currentUser.uid).once('value').then(function(snapshot) {
    var json = snapshot.val();
  });
相关问题