React js Socket.io和状态

时间:2019-11-22 16:26:13

标签: javascript node.js reactjs socket.io

您好,我正在尝试将套接字通过后端发送给我的响应保存为一种状态

这是一种向套接字发送消息的方法

export default class Home extends Component { 

    constructor(){
        super()

        this.state = {
          informationReceived: 'Nothing yet!'
        }
        const token = localStorage.getItem('token');
        const socket = io('http://localhost:8080', {
            query: { token: token }
        });

        socket.on('success', (receivedInfo) => {
            this.setState({
              informationReceived: receivedInfo
            })
          })

      }

      emitInfoToAll = () => {
        const token = localStorage.getItem('token');
        console.log('entrou')
        const socket = io('http://localhost:8080',{
            query: { token: token }
        });

        socket.emit('myevent', 'Hello realtime connected users!')
        console.log(this.state.informationReceived);
      }
}

但是这样,发送和接收时我将打开两次与套接字的连接 我想知道如何只能打开一个连接,所以当我向后端发送回复时,不必再次打开

以及如何设置为p的标签获取的这些值:

                <p> Name: <span className = "name"> </span> </p>
                <p> Points: <span className = "points"> 0 </span> </p>

1 个答案:

答案 0 :(得分:2)

您应该将socket设置为组件的状态,以便可以在emitInfoToAll方法中对其进行模拟

export default class Home extends Component { 

constructor(){
    super()

    this.state = {
      informationReceived: 'Nothing yet!'
      socket: null;
    }

    const token = localStorage.getItem('token');
    socket = io('http://localhost:8080', {
        query: { token: token }
    });

    socket.on('success', (receivedInfo) => {
        this.setState({
          informationReceived: receivedInfo
        })
      })

  }

  emitInfoToAll = () => {
    const { socket } = this.state;
    console.log('entrou')
    socket.emit('myevent', 'Hello realtime connected users!')
    console.log(this.state.informationReceived);
  }
}

更新:帮助将值设置为p标签

export default class Home extends Component {

    constructor() {
        super()

        this.state = {
            informationReceived: 'Nothing yet!',
            socket: null
        }

        const token = localStorage.getItem('token');
        socket = io('http://localhost:8080', {
            query: { token: token }
        });

        socket.on('success', (receivedInfo) => {
            this.setState({
                informationReceived: receivedInfo
            })
        })

    }

    emitInfoToAll = () => {
        const { socket } = this.state;
        console.log('entrou')
        socket.emit('myevent', 'Hello realtime connected users!')
        console.log(this.state.informationReceived);
    }

    render() {
        const { informationReceived } = this.state;
        const { name, point } = informationReceived;
        return (
            <div>
                <p> Name: <span className="name">{name}</span> </p>
                <p> Points: <span className="points">{point}</span> </p>
            </div>
        );
    }
}