首页 > 解决方案 > react/firebase 聊天中未处理的拒绝

问题描述

我使用 firebase 和 React 构建了一个聊天应用程序。当我向已与之聊天的用户发送消息时,效果很好。我还没有编写用于创建新聊天的函数,到目前为止,我只想查看控制台日志消息“新聊天”。

但是当firebase找不到数据库中已经存在的聊天时,它会抛出一个错误。我不知道为什么。 未处理的拒绝 (TypeError):无法读取未定义 DashboardComponent.addMsg 的属性“用户”

这是我的基础结构-收藏聊天-文档nata@gmail.com:pata@gmail.com(我的docKey)-消息和用户

我的基地结构

嵌套在仪表板中的新聊天组件:

class NewChatComponent extends React.Component {
  constructor(){
    super();
    this.state={
      friendsEmail: null,
      mess: null
    } 
  }
    
    submitForm = (e) => {
      //     pata@gmail.com
      const chat = this.docKey();
      this.chatExists() ? this.goToExistChat() : this.createChat();
      e.preventDefault();
    }
    createChat = () => {
      console.log('new chat')
    }

    goToExistChat = () => {
      const docKey = this.docKey();
      const mess = this.state.mess;
      this.props.goToExistChat(docKey, mess);
    }
    
    docKey = () => {
      const friend = this.state.friendsEmail;
      const docID = [this.props.email, friend].sort().join(':');
      console.log(`doc id : ` + docID)
      return docID;
    }

    chatExists = async () => {
      const docKey = this.docKey();
      const chat = await firebase
        .firestore()
        .collection('chats')
        .doc(docKey)
        .get();
        
      return chat.exists;
    }

父仪表板组件

class DashboardComponent extends React.Component {
      constructor() {
        super();
        this.state = {
          chats: [],
          email: null,
          selectedChat: null,
          chatVisible: false,
          newMessages: true,
          newChatFormVisible: false
        }    
      }
      
      render () {
        return (
            <div className='dashboard-cont'>
              <div className='dashboard'>
                <button className='newChatButton'
                  onClick={this.showNewChatForm}>
                  New Chat
                  </button>   
                  
                { this.state.newChatFormVisible ? <NewChatComponent email={this.state.email}
                goToExistChat={this.goToExistingChat}>
                  </NewChatComponent> :  null
                }                 
              </div>
            </div>
        )}
    
    
      goToExistingChat = async (docKey, msg) => {  
        const friend = docKey.split(':')[1];
        const chat = this.state.chats.find(chat => chat.users.includes(friend));
        const index = this.state.chats.indexOf(chat);
        await this.chooseChat(index);
        this.addMsg(msg);
      }
    
      buildDocId = (friend) => [this.state.email, friend].sort().join(':');
    
      //send msg to the chat & add msg to chat.messages array - THROWS AN ERROR IF FRIEND DOESN'T EXIST
      
     addMsg = (msg) => {
        const friend = this.state.chats[this.state.selectedChat].**users**.filter(user => user !== 
        this.state.email)[0];
        console.log(friend)
        const docId = this.buildDocId(friend);
        firebase
          .firestore()
          .collection('chats')
          .doc(docId)
          .update({
            messages: firebase.firestore.FieldValue.arrayUnion({
              message: msg,
              sender: this.state.email,
              timestamp: Date.now()
            })
          });
      }
    

标签: javascriptfirebasefirebase-realtime-database

解决方案


显然我应该将一个从承诺返回的值存储在一个变量中。

submitForm = async (e) => {
      e.preventDefault();
      const chat = this.docKey();
      const chatExists = await this.chatExists();
      chatExists ? console.log('pass to the exist chat') : console.log('create new one');
    }

而不是 this.chatExists() ?this.goToExistChat() : this.createChat();


推荐阅读