Firebase数据快照返回密钥但没有.val()

时间:2016-11-18 15:48:02

标签: javascript firebase react-native firebase-realtime-database

我有以下数据,其中查询user /(userID)/(topic)的值返回null:

{
  "topic" : {
    "cafe" : {
      "-KWoHbBXzWlD8aHBjg6Z" : {
        "count" : 0,
        "id" : "00qMXXXeYkbCbmjajoe4XZeIPuo1",
        "text" : "A new message",
        "time" : "2016-11-17T21:56:26.036Z"
      },
      "-KWpBzT83S_RB3wVwZ2u" : {
        "count" : 3,
        "id" : "zTSpSTqyRcaJf0MlYl15gBnvYdj2",
        "text" : "Hello",
        "time" : "2016-11-18T02:11:29.818Z"
      }
    },
    "pomodoro" : {
      "-KWoJhC9V1mLznt7jGwF" : {
        "count" : 3,
        "id" : "00qMXXXeYkbCbmjajoe4XZeIPuo1",
        "text" : "Tomato! #tomato",
        "time" : "2016-11-17T22:05:34.933Z"
      }
    }
  },
  "user" : {
    "00qMXXXeYkbCbmjajoe4XZeIPuo1" : {
      "pomodoro" : "2016-11-18T14:20:32.800Z"
    },
    "zTSpSTqyRcaJf0MlYl15gBnvYdj2" : {
      "cafe" : "2016-11-18T14:24:32.968Z"
    }
  }
}

以下是相关代码:

// inside the constructor
this.database = firebase.database().ref()

//relevant function
databaseListenerOn = () => {

  // does not work correctly
  let userPath = `user/${this.props.userID}/${this.state.topic}`
  this.database.child(userPath).on('value', data => {
    this.setState({time: data.val()})
    console.log(data.key)
    console.log(data.val())
  })

  //works correctly 
  let messagePath = `topic/${this.state.topic}`
  this.database.child(messagePath).on('value', data => {
    let messages = []
    data.forEach(message => {
      messages.push({
        count: message.val().count,
        id: message.val().id,
        key: message.key,
        text: message.val().text,
        time: message.val().time
      })
    })
    this.setState({messages: this.state.messages.cloneWithRows(messages)})
  })
}

记录data.key正确返回“咖啡馆”#39;或者' pomodoro'。但是,data.val()返回null,我无法访问字符串时间戳。

使用类似的代码,我能够成功访问其中data.val()返回对象的其他数据,因此我对可能出错的内容感到困惑。我在本网站和谷歌集团看过类似的问题,但没有找到我的具体情况的答案。

1 个答案:

答案 0 :(得分:1)

问题是我在运行查询之前没有等待Firebase返回用户ID:

// this.props.userID is undefined    
let userPath = `user/${this.props.userID}/${this.state.topic}`

解决方案是在this.databaseListenerOn()内调用onAuthStateChanged以确保在我拥有用户ID后调用它。

相关问题