【问题标题】:Firebase - Getting data from child sometimes returns unknownFirebase - 从孩子那里获取数据有时会返回未知数
【发布时间】:2021-05-29 20:49:51
【问题描述】:

我正在使用 Firebase 构建一个带有 React Native 的 Android 应用程序来实现用户之间的聊天。我现在正在运行测试,发现有时发送聊天消息会产生以下异常并使应用程序崩溃:

Reference.child 失败:第一个参数是无效路径 =“未定义”。路径必须是非空字符串,并且不能包含“.”、“#”、“$”、“[”或“]”

这是向 Firebase 实时数据库发送消息的函数,只要按下“发送消息”按钮就会触发:

sendMessageToFirebase(chatId, userId){
  let newMessage = {created: new Date().toJSON(), text: this.state.textInput}
  //getting messages data from firebase
  let data = {};
  console.log('REF:' + firebase.database().ref('chats'));
  dataRef = firebase.database().ref('chats').child(chatId);
  console.log('REF WITH CHILD: ' + dataRef);
  dataRef.on('value', datasnap=>{
      data = datasnap.val()
      //the following function rewrites the dictionary fetched from FB to add the new message
      data = this.rewriteFirebaseChatData(data, userId, newMessage);
  })
  //sending the data
  dataRef.set(data)
  this.loadMessagesFromFirebase(chatId);
}

第一个控制台日志,只有 ref,总是会打印,但在看似随机的基础上,第二个 ref 不会,我会得到异常,所以我可以假设问题出在哪里。有没有办法可靠地从孩子那里获取数据?

【问题讨论】:

  • 在你有“child(chatId)”的那一行上,如果这个变量被正确传递,chatId 来自于检查你的日志

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


【解决方案1】:

如果错误来自您共享的代码,则chatId 似乎是undefined

您需要检查调用代码为什么会发生这种情况。如果这是一个有效的情况,您也需要在 sendMessageToFirebase 中检查它,例如将其添加到方法的开头:

if (!chatId) return;

【讨论】:

  • 非常感谢。组件状态中的 chatId 设置不正确。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-28
  • 2021-04-02
相关资源
最近更新 更多