使用Effect运行两次一旦从socket.io接收消息

发布于 2025-01-25 01:47:30 字数 1779 浏览 4 评论 0原文

我正在使用React,Express和Socket.io构建一个简单的聊天应用程序。

每当客户端将消息发送到服务器时,服务器都会向每个用户广播消息。从后端服务器收到消息时,我有问题。

每次用户收到消息时,useffect将运行两次,而不是一次。

useEffect(() => {
    socket.on("broadcast_msg", (data) => {
      setMsg((list) => [...list, data]);
    });
  }, [socket]);

PS。后端服务器仅发出一次前端。 谢谢您的每一个回复:D

整个代码

import React from "react";
import { useEffect } from "react";
import { useState } from "react";

function Chat(props) {
  const { socket, username, room } = props;
  const [input, setInput] = useState("");
  const [msg, setMsg] = useState([]);

  // send msg to server
  const send_msg = (e) => {
    if (input !== "") {
      socket.emit("send_msg", {
        room: room,
        author: username,
        message: input,
      });
    }
  };

  // listen to boardcast msg
  useEffect(() => {
    socket.on("broadcast_msg", (data) => {
      setMsg((list) => [...list, data]);
    });
  }, [socket]);

  return (
    <div className="chat">
      <div className="chat-header"></div>
      <div className="chat-body">
        {msg.map((data) => {
          return (
            <>
              <h1>{data.author}</h1>
              <h1>{data.room}</h1>
              <h1>{data.message}</h1>
            </>
          );
        })}
      </div>
      <div className="chat-footer">
        <input
          type="text"
          placeholder="Enter the message..."
          onChange={(e) => {
            setInput(e.target.value);
          }}
        />
        <button onClick={send_msg}>Send</button>
      </div>
    </div>
  );
}

export default Chat;

I am building a simple chat application using react, express, and socket.io.

Every time that client sends the message to the server, the server will broadcast the message back to every user. I have a problem when receiving a message back from the backend server.

Every time user receives a message, the useEffect will run twice instead of only once.

useEffect(() => {
    socket.on("broadcast_msg", (data) => {
      setMsg((list) => [...list, data]);
    });
  }, [socket]);

PS. The backend server emits back to the front-end only once.
Thank you for every response :D

Whole Code

import React from "react";
import { useEffect } from "react";
import { useState } from "react";

function Chat(props) {
  const { socket, username, room } = props;
  const [input, setInput] = useState("");
  const [msg, setMsg] = useState([]);

  // send msg to server
  const send_msg = (e) => {
    if (input !== "") {
      socket.emit("send_msg", {
        room: room,
        author: username,
        message: input,
      });
    }
  };

  // listen to boardcast msg
  useEffect(() => {
    socket.on("broadcast_msg", (data) => {
      setMsg((list) => [...list, data]);
    });
  }, [socket]);

  return (
    <div className="chat">
      <div className="chat-header"></div>
      <div className="chat-body">
        {msg.map((data) => {
          return (
            <>
              <h1>{data.author}</h1>
              <h1>{data.room}</h1>
              <h1>{data.message}</h1>
            </>
          );
        })}
      </div>
      <div className="chat-footer">
        <input
          type="text"
          placeholder="Enter the message..."
          onChange={(e) => {
            setInput(e.target.value);
          }}
        />
        <button onClick={send_msg}>Send</button>
      </div>
    </div>
  );
}

export default Chat;

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

莫言歌 2025-02-01 01:47:30
useEffect(() => {
    const eventListener = (data) => {
        setMsg((list) => [...list, data]);
    };
    socket.on("broadcast_msg", eventListener);

    return () => socket.off("broadcast_msg", eventListener);
  }, [socket]);

与听众一起做。
运行使用效果并清洁侦听器时再次触发,这应该可以解决问题。
或安装时仅运行一次。

 useEffect(() => {
    socket.on("broadcast_msg", (data) => {
      setMsg((list) => [...list, data]);
    });
  }, []);
useEffect(() => {
    const eventListener = (data) => {
        setMsg((list) => [...list, data]);
    };
    socket.on("broadcast_msg", eventListener);

    return () => socket.off("broadcast_msg", eventListener);
  }, [socket]);

Do with listener.
Run useEffect and clean the listener when fired again, this should do the trick.
or run only once when mounted.

 useEffect(() => {
    socket.on("broadcast_msg", (data) => {
      setMsg((list) => [...list, data]);
    });
  }, []);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文