socketio套接字更改为未定义

时间:2019-02-08 21:46:37

标签: javascript reactjs typescript socket.io typescript2.0

im尝试使用NPM软件包socket.io-client和reactjs构建身份验证。我使用Visual Studio Code作为我的IDE,并使用create-react-app --typescript包作为我的前端代码。我遇到的问题是我打开了一个套接字,由于某种原因,我在两行之后将套接字存储在undefined的更改中。而且我无法弄清楚在后台会发生什么重置我的变量。

我在componentDidMount中打开套接字,后端有一个连接事件处理程序:

socketServer.on("connection", (test) => {
  console.log("Socket.io:OnConnection: User Connected");
});

我看到套接字正在连接,但是之后this.socket变为undefined仅两行。如果我在io('http://localhost:3001')的同一行中打印出console.log(),则整个对象将像这样打印出来:

{…}​_callbacks: Object { "$connecting": (1) […], "$connect": (1) […], "$authentication": (1) […] }​acks: Object {  }​connected: true​disconnected: false​flags: Object {  }​id: "-rKYuFfknSQdonUFAAAC"​ids: 0​io: Object { _reconnection: true, _reconnectionDelay: 1000, _reconnectionDelayMax: 5000, … }​json: Object { nsp: "/", ids: 0, connected: true, … }​nsp: "/"​receiveBuffer: Array []​sendBuffer: Array []​subs: Array(3) [ {…}, {…}, {…} ]​<prototype>: Object { addEventListener: addEventListener(), on: addEventListener(), once: once(), … } LoginButton.tsx:21

但是之后的任何console.log()都会返回undefined

我希望你们能帮助我解决这个问题。

这是我的组件

import * as React from "react";
import { RouteComponentProps, withRouter } from "react-router";
import {Menu} from "semantic-ui-react";
import io from "socket.io-client";

class LoginButton extends React.Component<RouteComponentProps> {

    private socket: any;
    private popup!: Window | null;

    public constructor(props: RouteComponentProps) {
        console.log(__filename, 'constructor',);
        super(props);
        this.state = {};
    }

    public componentDidMount() {
        console.log(`${__filename}: ${this.componentDidMount.name}`);
        // Connects to backend API url
        this.socket = io('http://localhost:3001');
        console.log(`${this.componentDidMount.name}: SocketID: ${this.socket.id}`);
        this.socket.on('authentication', (jwt: string) => console.log(`Got JWT! ${jwt}`));
    }

    public componentWillUnmount() {
        // Closes the socket when component unmounts
        console.log(`${this.componentWillUnmount.name}: Will Really unmount????`);
        // this.socket.disconnect();
    }

    public handleLogin(): void {
        console.log('SocketId:', this.socket);
        this.popup = window.open(
            `http://localhost:3001/api/v1/steam/auth?socketId=${this.socket.id}`,
            "_blank",
            "width=800, height=600"
          );

          if (window.focus) {
            this.popup!.focus();
          }
    }

    public render() {
        return <Menu.Item name="login" onClick={this.handleLogin} />;
    }
}

export default withRouter(LoginButton);

0 个答案:

没有答案