簡體   English   中英

在Firebase中訪問2個關鍵數據

[英]Access 2 key data in Firebase

我可以訪問密鑰的第一個數據,但是不能訪問密鑰路徑的下一個數據。 當我輸入'value'而不是'child_added'時,我得到第一個路徑的數據,但是我需要訪問phot中顯示的路徑中的所有數據

    class App extends Component {
      constructor(props) {
        super(props)
        this.state = {
          users: []
        }
        this.exportFile = this.exportFile.bind(this)
    }

    componentWillMount(){
      this.getUsers()
      this.getdataIDs()
    }

    getUsers() {
      let users = []

      // uncommented line gives an error
      /*var eventID = firebase.database().ref(`conversationEnrolments`).once('value')*/
      var path = firebase.database().ref(`conversationEnrolments`)
      path.once('child_added', snapshot => {
         snapshot.forEach(snap => {
         users.push(snap.val())
      })
      this.setState({
        users
      })
    })
   }

最后一條路徑的值不顯示

您的問題來自以下事實: once()方法“僅偵聽指定事件類型的一個事件,然后停止偵聽”。 如文檔中的詳細信息, 在此處

因此,這就是為什么只獲得一個孩子的值的原因,即具有-LDHYq... id的孩子的值。

如果要獲取conversationEnrolments節點下的項目的完整列表,請使用'value'事件並執行以下操作:

    var ref = firebase.database().ref('conversationEnrolments');
    ref.once('value', function (data) {
        data.forEach(snap => {
            console.log(snap);
            console.log(snap.val());
        });
    });

然后,您的代碼中出現了第二個問題:由於after()方法是異步的 ,並且返回了一個Promise(請參閱doc ),因此您需要等待此Promise解析后才能使用users變量,如下所示。 查看執行不同console.log()的順序。

    let users = []

    var ref = firebase.database().ref('conversationEnrolments')
    ref.once('value', function (data) {
        data.forEach(snap => {
            console.log(snap);
            console.log(snap.val());
            users.push(snap.val());
        });
    }).then(() => {
        //Here, the promise has resolved and you get the correct value of the users array
        console.log("users AFTER promise has resolved");
        console.log(users);
    })
    console.log("users BEFORE promise has resolved");
    //Here the console.log prints the value of the array before the promise has resolved and.... it is empty!
    console.log(users);

更新:如何將此代碼封裝在函數中。

    function getUsers() {

        let users = []
        var ref = firebase.database().ref('conversationEnrolments');
        return ref.once('value', function (data) {  //The function returns the result of the promise
            data.forEach(snap => {
                users.push(snap.val());
            });
        }).then(() => {
            return users;  
        })
    }

    //The getUsers() is asynchronous
    //Call it as follows: since it returns a promise, use the result within the then().
    getUsers().then((users) => { console.log(users) });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM