反应 Pubnub 聊天。消息重复或根本没有消息

React Pubnub Chat. Message dublication or no message at all

我的 React 网站一直存在问题。我们正在使用 pubnub SDK 创建一个聊天组件,这样人们就可以互相聊天了。所有频道管理都已完成,但问题是每次切换频道时所有消息都会被复制,而且它们只会在 Dom 中被复制。 PubNub 的历史记录 API returns 只有一条消息,但只有在刷新后才会出现,因为该组件仅在挂载或频道更改时获取历史消息。

这是负责消息的代码

export default function Chat({ chatRoom, person, task }) {
  const [messages, addMessage] = useState([]); //messages that are being mapped in the JSX
  const [message, setMessage] = useState("");//set by the input field in the JSX


//adding the pubnub listeners on mount
  useEffect(() => {
    console.log("ADDING LISTENER");

    pubnub.addListener({
      message: (message) => {
        if (message) {
          addMessage((messages) => [...messages, message]);
          console.log(message.message);
        }
        scrollingComponent.current.scrollIntoView({ behavior: "smooth" });
      },
      file: handleFile,
    });

    pubnub.subscribe({ channels: [chatRoom] });

//cleaning listeneres on dismount
    return function cleanup() {
      pubnub.removeListener({
        message: (message) => {
          if (message) {
            addMessage((messages) => [...messages, message]);
            console.log(message.message);
          }
          scrollingComponent.current.scrollIntoView({ behavior: "smooth" });
        },
        file: handleFile,
      });

      pubnub.unsubscribeAll();
      addMessage([]);
    };
  }, [chatRoom]);



//added this function and it's coresponding useEffect just to test if thats the cause of the dublication. Before that the function sendMessage had the body of the use effect
const sendMessage = (m) => {
  console.log(m);
  setMessage("");
};

  useEffect(() => {
    if (message) {
      pubnub
        .publish({
          channel: chatRoom,
          message: message,
          storeInHistory: true,
        })
        .then(() => {
          pubnub.signal({
            channel: chatRoom,
            message: "notification",
          });
          pubnub.signal({
            channel: chatRoom,
            message: "not_typing",
          });
        })
        .catch((error) =>
          addMessage((messages) => [...messages, error.toString()])
        );
    }
  }, [sendMessage]);

//code continues...

如果需要,我可以 post 整个 .js 文件

您的代码中的问题是您没有正确删除侦听器。您正在重新创建相同的函数两次(但不是同一个函数),因此 PubNub SDK 不会将其从侦听器中删除。

相反,您应该在第一个 useEffect 中执行类似的操作:

//adding the pubnub listeners on mount
useEffect(() => {
  const listener = { // <-- extract the listener
    message: (message) => {
      if (message) {
        addMessage((messages) => [...messages, message]);
        console.log(message.message);
      }
      scrollingComponent.current.scrollIntoView({ behavior: "smooth" });
    },
    file: handleFile,
  }
  

  pubnub.addListener(listener); // <-- pass the listener here

  pubnub.subscribe({ channels: [chatRoom] });
  
  return function cleanup() {
    pubnub.removeListener(listener); // <-- pass the same listener here

    pubnub.unsubscribeAll();
    addMessage([]);
  };
}, [chatRoom]);