Dapatkan pemberitahuan penyemak imbas daripada sesiapa sahaja kecuali pengesah semasa. pengguna
P粉161939752
P粉161939752 2024-04-04 19:01:28
0
1
431

Saya sedang membina apl sembang dalam React JS dan saya sudah gila dengan masalah ini sejak dua hari lalu. Saya mahu membuatnya supaya apabila terdapat mesej baharu, pemberitahuan penyemak imbas muncul.

Masalahnya ialah saya hanya mendapat pemberitahuan apabila saya menghantar mesej, bukan apabila orang lain menghantar mesej. Keadaan sebenar sepatutnya sebaliknya.

Saya menggunakan pakej npm react-push-notification untuk mencapai ini.

Chat.js:

import { useEffect, useState } from "react";
import { addDoc, collection, serverTimestamp, onSnapshot, query, where, orderBy } from "firebase/firestore";
import { auth, db } from "../firebase-config";
import "../styles/Chat.css";
import IDLogo from "../images/IDLogo.png";
import notificationSound from "../sounds/message_sound.mp3";
import addNotification from "react-push-notification";
import DefaultProfilePicture from "../images/default_pfp.jpeg";

export const Chat = props => {
  const { room } = props;
  const [newMessage, setNewMessage] = useState();
  const [messages, setMessages] = useState([]);

  const messagesRef = collection(db, "messages");

  useEffect(() => {
    const queryMessages = query(messagesRef, where("room", "==", room), orderBy("createdAt"));
    const unsubscribe = onSnapshot(queryMessages, snapshot => {
      let messages = [];
      snapshot.forEach(doc => {
        messages.push({ ...doc.data(), id: doc.id });
      });
      setMessages(messages);
    });

    return () => unsubscribe();
  }, []);

  useEffect(() => {
    const messagesContainer = messagesRef.current;
    messagesContainer.scrollTop = messagesContainer.scrollHeight;
  }, [messagesRef]);

  const handleSubmit = async e => {
    e.preventDefault();
    if (newMessage === "") return;

    const currentUser = auth.currentUser;

    await addDoc(messagesRef, {
      text: newMessage,
      createdAt: serverTimestamp(),
      user: currentUser.displayName,
      profilePicture: currentUser.photoURL,
      room,
    });

    if (newMessage && newMessage.user !== auth.currentUser.displayName) {
      addNotification({
        title: "New Message",
        message: newMessage.text,
        duration: 5000,
        native: true,
        icon: IDLogo,
      });
    }

    setNewMessage("");
  };

  useEffect(() => {
    const audio = new Audio(notificationSound);
    const lastMessage = messages[messages.length - 1];

    if (lastMessage && lastMessage.user !== auth.currentUser.displayName) {
      audio.play();
    }
  }, [messages]);

  return (
    <div className='chat'>
      <div className='header'>
        <h1>
          Welcome to: <span className='Chat__room--title'>{room.toUpperCase()}</span>
        </h1>
      </div>

      <div ref={messagesRef} className='messages'>
        {messages.map(message => (
          <p className='Chat__message'>
            {message.profilePicture ? (
              <img className='profile__picture' referrerpolicy='no-referrer' src={message.profilePicture} alt={message.user} />
            ) : (
              <img className='profile__picture' src={DefaultProfilePicture} alt={message.user}></img>
            )}
            {message.user} : {message.text}
          </p>
        ))}
      </div>
      <div className='send__message__container'>
        <form onSubmit={handleSubmit} className='new__message__form'>
          <input
            spellCheck='false'
            onChange={e => setNewMessage(e.target.value)}
            className='new__message__input'
            placeholder='Type a message here...'
            value={newMessage}
          />
          <button type='submit' className='signOut--sendMessage__button'>
            Send
          </button>
        </form>
      </div>
    </div>
  );
};

P粉161939752
P粉161939752

membalas semua(1)
P粉195402292

Hanya alihkan fungsi pemberitahuan tambah daripada fungsi penyerahan pemegang:

if (newMessage && newMessage.user !== auth.currentUser.displayName) {
  addNotification({
    title: "New Message",
    message: newMessage.text,
    duration: 5000,
    native: true,
    icon: IDLogo,
  });
}

Bawa ke kegunaan seterusnyaKesan:

useEffect(() => {
const audio = new Audio(notificationSound);
const lastMessage = messages[messages.length - 1];

if (lastMessage && lastMessage.user !== auth.currentUser.displayName) {
  audio.play();
  addNotification({
   title: "New Message",
   message: newMessage.text,
   duration: 5000,
   native: true,
   icon: IDLogo,
  });
}}, [messages]);
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan
Tentang kita Penafian Sitemap
Laman web PHP Cina:Latihan PHP dalam talian kebajikan awam,Bantu pelajar PHP berkembang dengan cepat!