在我的根组件上,我像这样设置套接字,
const [socket, setSocket] = useState(null);
const setupSocket = () => {
const token = localStorage.getItem('CC_Token');
if (token && token.length > 0 && !socket) {
const newSocket = io('http://localhost:8000', {
query: {
token: localStorage.getItem('CC_Token'),
},
});
newSocket.on('disconnect', () => {
setSocket(null);
setTimeout(setupSocket, 3000);
makeToast('error', 'Socket disconnected!');
});
newSocket.on('connect', () => {
makeToast('success', 'Socket Connected');
});
setSocket(newSocket);
}
};
useEffect(() => {
setupSocket();
}, []);
并使用react-router我将套接字实例作为道具传递。
<Route
exact
path="/chatroom/:id"
render={() => <ChatroomPage socket={socket} />}
/>;
直到我刷新页面为止,它都可以正常工作。当我刷新页面套接字时,它返回到其初始状态(空),因此,我无法发送任何消息。
此代码段来自CharoomPage
组件。
React.useEffect(() => {
if (socket) {
socket.emit("joinRoom", {
chatroomId,
});
}
return () => {
//Component Unmount
if (socket) {
socket.emit("leaveRoom", {
chatroomId,
});
}
};
//eslint-disable-next-line
}, []);
在页面上的刷新套接字为null,因此它无法发出joinRoom
事件。
如何实现此功能,以便在页面刷新时发出joinRoom
事件?
好吧,如果刷新页面,套接字将返回到初始状态null
,并且useEffect
应该运行。
但是你的ChatRoomPage useEffect不考虑socket
第二个参数。
尝试一下
const ChatRoom = ({socket}) => {
useEffect(() => {
if( !socket) return;
socket.emit("joinRoom", {chatroomId});
return () => {
if (!socket) return;
socket.emit("leaveRoom", {chatroomId});
};
}, [socket]); //<== here
};
你的错误的奇怪之处在于它有时在刷新之前就可以使用。