【问题标题】:How to hold the socket instance on page refresh?如何在页面刷新时保持套接字实例?
【发布时间】:2021-03-10 19:18:44
【问题描述】:

在我的根组件上,我正在像这样设置套接字,

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} />}
/>;

它工作正常,直到我刷新页面。当我刷新页面套接字时,它会恢复到其初始状态(null),因此我无法发送任何消息。

这个 sn-p 来自CharoomPage 组件。

  React.useEffect(() => {
    if (socket) {
      socket.emit("joinRoom", {
        chatroomId,
      });
    }

    return () => {
      //Component Unmount
      if (socket) {
        socket.emit("leaveRoom", {
          chatroomId,
        });
      }
    };
    //eslint-disable-next-line
  }, []);

页面刷新套接字为空,因此无法发出joinRoom 事件。

如何实现这一点,以便在页面刷新时发出 joinRoom 事件?

【问题讨论】:

    标签: javascript reactjs sockets socket.io real-time


    【解决方案1】:

    如果你刷新页面,socket 会回到初始状态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
    };
    

    您的错误的奇怪部分是它有时会在刷新之前起作用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-11-27
      • 2018-07-25
      • 2014-07-21
      • 2014-05-06
      • 1970-01-01
      • 1970-01-01
      • 2017-03-08
      相关资源
      最近更新 更多