【问题标题】:How to use react-native-gifted-chat with cloud firestore?如何将 react-native-gifted-chat 与 Cloud Firestore 一起使用?
【发布时间】:2019-10-17 05:59:27
【问题描述】:

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

【问题讨论】:

  • 来自Stackoverflow issue 的该用户声称已使用 react-native-gifted-chat 解决了他们的问题。如果您仔细观察,您会看到用于获取可能对您自己的应用程序有用的消息的示例代码。您也可以查看此GitHub repo。随时通知我。

标签: javascript react-native google-cloud-firestore chat react-native-gifted-chat


【解决方案1】:

我已经能够使用与GitHib repo 类似的方法在我的应用上运行它

我的代码调用 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);
        });
      });
  }

如果您有任何问题,请联系我们!

【讨论】:

  • 你能分享一下你是如何处理聊天的代码链接,或者你在firestore中使用的数据结构的截图吗?