【问题标题】:Retrieving Data from Firebase child object in React Native从 React Native 中的 Firebase 子对象检索数据
【发布时间】:2017-12-11 20:07:17
【问题描述】:

我正在尝试从 react 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());

【问题讨论】:

    标签: react-native


    【解决方案1】:

    如果你的火力基地结构,你有一个进一步的巢穴

    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
        });
    

    【讨论】:

    • 非常感谢。我后来才知道这件事。非常感谢您的帮助。
    【解决方案2】:

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

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

    【讨论】:

    • 是的,但它存储子对象的值。我想得到里面元素的值。由于我在 firebase 中推送对象而不是使用 .set 函数,因此每次都会创建一个新的子 ID。我们将需要遍历父对象以使用子对象的键获取所有元素。
    猜你喜欢
    • 1970-01-01
    • 2019-03-25
    • 1970-01-01
    • 1970-01-01
    • 2020-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多