我有这个代码:
useEffect(() => {
const init = async () => {
try {
socketRef.current = await initSocket();
socketRef.current.on("connect_error", (err) => handleErrors(err));
socketRef.current.on("connect_failed", (err) => handleErrors(err));
function handleErrors(e) {
console.log("socket error", e);
toast.error("Socket connection failed, try again later.");
navigate("/dashboard");
}
function DisconnectRoom({ socketId, username }) {
toast.info(`${username} left the room`);
setClients((prev) => {
return prev.filter((client) => client.socketId !== socketId);
});
}
function JoinedRoom({ clients, userName, socketId }) {
if (username !== userName) {
toast.success(`${userName} joined the room!`);
socketRef.current.emit(Actions.SYNC_CODE, {
roomId,
code: codeRef.current,
socketId,
name: "all",
});
}
setClients(clients);
}
socketRef.current.emit(Actions.JOIN, {
roomId,
username,
});
socketRef.current.on(Actions.JOINED, JoinedRoom);
socketRef.current.on(Actions.DISCONNECTED, DisconnectRoom);
} catch (e) {
console.log(e);
}
};
init();
return () => {
socketRef.current.disconnect();
socketRef.current.off(Actions.DISCONNECTED);
socketRef.current.off(Actions.JOINED);
};
}, []);
问题是当 cleanup 函数执行时,它会给出一个错误:socketRef.current 为 null。我已经尝试提出一个条件 -
if(socketRef.current) {
socketRef.current.disconnect();
socketRef.current.off(Actions.DISCONNECTED);
socketRef.current.off(Actions.JOINED);
}
但是现在它连接客户端两次,可能是因为在严格模式下 React 调用函数两次。谁能帮我解决这个问题
我尝试将一个客户端连接到套接字,但如上所述,如果我检查 socketRef.current ,那么它会连接客户端两次,如果我不这样做,它会给出 socketRef.current 为 null 的错误。
套接字连接是否需要使用引用?为什么不在 useEffects 范围内使用变量来跟踪您的套接字实例?
伪代码:
let socket;
socket = createConnection();
return () => {
if (socket) {
socket.disconnect();
}
}