我尝试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
执行了两次,我该如何解决这个问题?
以下答案第一版后的错误截图:
1条答案
按热度按时间mmvthczy1#
我认为您的
createMessag
侦听器在内存中注册了两次,可能是因为重新呈现或StrictMode
。