我有以下数据,其中查询用户/(UserID)/(主题)的值将返回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正确地返回‘咖啡厅’或‘波奥多罗’。但是,data.val()返回null,我无法访问字符串时间戳。
使用类似的代码,我能够成功地访问data.val()返回对象的其他数据,因此我对自己可能做错了什么感到困惑。我曾在这个网站和谷歌集团上看过类似的问题,但没有找到我的特殊情况的答案。
发布于 2016-11-18 18:38:36
问题是,在运行查询之前,我没有等待Firebase返回userID:
// this.props.userID is undefined
let userPath = `user/${this.props.userID}/${this.state.topic}`解决方案是在onAuthStateChanged中调用onAuthStateChanged,以确保一旦有了userID就调用它。
https://stackoverflow.com/questions/40681126
复制相似问题