next.js 为什么Socket.ioReact中的www.example.com客户端执行所有事件两次?

yc0p9oo0  于 2023-01-17  发布在  React
关注(0)|答案(1)|浏览(110)

我尝试Socket.io在Next.js应用程序中使用www.example.com客户端,但我面临一个问题;当我执行一个事件套接字运行两次。2但我没有找到任何解决办法。3有人能帮我调试这个问题吗?
我正在使用React Context创建套接字提供程序。
socket.context.tsx -

import { createContext, FC, useContext } from "react";
import { io, Socket } from "socket.io-client";
import { getCookie } from "cookies-next";

const token = getCookie("session")

const socket = io(process.env.NEXT_PUBLIC_WS || "http://localhost:5000", {
    extraHeaders: {
        "authorization": token?.toString() || ""
    }
})

//types
interface SocketContextInterface {
    socket: Socket
}
const SocketContext = createContext<SocketContextInterface>({ socket });

interface Props {
    children: React.ReactNode
}

const SocketProvider: FC<Props> = (props) => {
    return (
        <SocketContext.Provider value={{ socket }}>
            {props.children}
        </SocketContext.Provider>
    );
};

export const useSocket = () => useContext(SocketContext)

export default SocketProvider;

然后,我把它用在一个部件上-

const { socket } = useSocket();

//Performing create message on onSubmit handler
const onSubmit: SubmitHandler<Inputs> = (submitData) => {
    const MessageData = {
        conversation: selected,
        message: {
            text: submitData.message
        }
    }
    socket.emit("createMessage", MessageData);
    reset();
}

//And then I am try to listen event

useEffect(() => {
    socket.on("createMessage", (data: MessageData) => {
        setMessages((prev: MessageData[]) => [...prev, data])
    })
}, [socket])
// But this performs two times

这里socket.on执行了两次,我该如何解决这个问题?

以下答案第一版后的错误截图:

mmvthczy

mmvthczy1#

我认为您的createMessag侦听器在内存中注册了两次,可能是因为重新呈现或StrictMode

useEffect(() => {
  const listener = (data: MessageData) => {
    setMessages((prev: MessageData[]) => [...prev, data]);
  };
  socket.on("createMessage", listener);
  return () => {
    socket.off("createMessage", listener);
  };
}, [socket]);

相关问题