【问题标题】:Firebase data snapshot returns key but no .val()Firebase 数据快照返回键但没有 .val()
【发布时间】:2016-11-18 15:48:01
【问题描述】:

我有以下数据,其中查询 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)})
  })
}

logging data.key 正确返回“cafe”或“pomodoro”。但是,data.val() 返回 null,我无法访问字符串时间戳。

使用类似的代码,我能够成功访问 data.val() 返回对象的其他数据,因此我对自己可能做错了什么感到困惑。我在这个网站和 Google Group 上查看过类似的问题,但没有找到适合我的特殊情况的答案。

【问题讨论】:

  • 您在问题中包含了 JSON 树的图片。请将其替换为实际的 JSON 作为文本,您可以通过单击 Firebase 数据库控制台中的导出按钮轻松获取该文本。将 JSON 作为文本使其可搜索,让我们可以轻松地使用它来测试您的实际数据并在我们的答案中使用它,一般来说这只是一件好事。
  • 代码乍一看还不错。你能设置一个最小的 JSBin 来重现这个问题吗?
  • 我以前从未使用过 JSBin,但我会看看是否可以复制该问题。现在,我已将 JSON 添加为文本以及一些附加信息。
  • 一个 jsfiddle 或类似的东西也可以。我主要只是想看到问题发生,因为我可能忽略了代码中的某些内容。
  • jsbin.com/nicecilowu/1/edit?js,console,output(我希望我正确地分享了这个)当我尝试隔离查询时,数据被正确返回,所以它一定是我的 react-native 应用程序中的其他东西导致了问题。但是,我不确定为什么 databaseListenerOn 中的其他 .on 方法可以正常工作:/

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


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-05
    • 1970-01-01
    • 1970-01-01
    • 2021-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多