首页 > 解决方案 > 如何将 react-native-gifted-chat 与 Cloud Firestore 一起使用?

问题描述

我在使用 cloud firestore 时遇到了 react-native-gifted-chat 的问题。我无法获取以前的消息并附加到有天赋的聊天中。请向我展示如何与云 Firestore 一起使用的代码。谢谢

标签: javascriptreact-nativegoogle-cloud-firestorechatreact-native-gifted-chat

解决方案


我已经能够使用与在GitHib 存储库中找到的方法类似的方法在我的应用程序上运行它

我的代码调用 componentDidMount 中的 loadMessages 函数,该函数使用 onSnapshot 来跟踪我的 Message 或 Chats 集合中的任何更改。如果发生更改,它会使用回调函数将新消息附加到 GiftedChat。

这是我的代码:

async componentDidMount() {    
    this.loadMessages(message => {
      this.setState(previousState => {
        return {
          messages: GiftedChat.append(previousState.messages, message)
        };
      });
    });

  }
async loadMessages(callback) {
    var that = this;
    var recipientId = this.props.navigation.getParam("recipientId");
    var chatId = this.generateChatID(recipientId);

    this.setState({ chatId });
    firebase
      .firestore()
      .collection("Message")
      .doc(chatId)
      .collection("Chats")
      .orderBy("createdAt", "asc")
      .onSnapshot(function(doc) {
        doc.docChanges().forEach(chat => {
          var id = chat.doc.id;
          chat = chat.doc.data();
          const newMessage = {
            _id: id,
            text: chat.text,
            createdAt: chat.createdAt.toDate(),
            user: {
              _id: chat.user._id,
              name: chat.user.name,
              avatar: chat.avatar
            }
          };
          callback(newMessage);
        });
      });
  }

Lmk如果你有任何问题!


推荐阅读