使用 socket.io 在聊天应用程序中与打字稿作斗争

Struggling with typescript in chat application using socket.io

我正在使用 socket.io 和打字稿构建一个实时通知应用程序,当我尝试将事件从客户端发送到服务器时,它显示错误。下面是我更新状态时的代码,它在浏览器 window 中显示错误“无法读取 null 的属性(读取 'emit')”

  const [socket, setSocket] = useState<any>(null)

  useEffect(()=>{
    setSocket(io("http://localhost:5000"));
   
  },[])

  useEffect(()=>{
    socket.emit("newUser", user);
  },[socket,user])

最有可能的是,您的发射失败是因为您在建立连接之前调用它的时间过早。

socket.on("connect", () => {
  console.log(socket.id); // x8WIv7-mJelg7on_ALbx
  socket.emit("hello", { a: "b", c: [] });
});