1

现在在我的应用程序中,一对一聊天正在工作,但是我想使用 firebase 添加群聊功能。

4

1 回答 1

1

首先,您需要在 firebase 中创建一个聊天室

const [roomName, setRoomName] = useState('');

const createRoom = () => {
if (roomName.length > 0) {
  firestore()
    .collection('THREADS')
    .add({
      name: roomName,
      latestMessage: {
        text: `You have joined the room ${roomName}.`,
        createdAt: new Date().getTime(),
      },
    })
    .then(docRef => {
      docRef.collection('MESSAGES').add({
        text: `You have joined the room ${roomName}.`,
        createdAt: new Date().getTime(),
        system: true,
      });
    });
}};

然后,您可以使用线程 ID 从房间获取消息

const [messages, setMessages] = useState([]);

const {thread} = route.params;

useEffect(() => {
const messagesListener = firestore()
  .collection('THREADS')
  .doc(thread._id)
  .collection('MESSAGES')
  .orderBy('createdAt', 'desc')
  .onSnapshot(querySnapshot => {
    const messages = querySnapshot.docs.map(doc => {
      const firebaseData = doc.data();

      const data = {
        _id: doc.id,
        text: '',
        createdAt: new Date().getTime(),
        ...firebaseData,
      };

      if (!firebaseData.system) {
        data.user = {
          ...firebaseData.user,
          name: firebaseData.user.email,
        };
      }

      return data;
    });

    setMessages(messages);
  });

return () => messagesListener();
}, []);
于 2022-02-14T10:16:32.923 回答