反应/生命周期

时间:2019-11-25 02:37:22

标签: javascript reactjs

我想建立一个具有套接字服务器的我的api的连接,我将在其中实时交换信息

然后,我需要通过api的每条新消息返回来更新一些组件,但是我对使用什么有一点疑问, 以componentWillMount

作为我与后代的联系

以及我在componentDidMount中的连接和套接字事件

以及我将如何创建一个上下文,以便每当我的后端更改每个套接字时,使某些组件保持最新状态

如果有人能提供一个例子,我将非常感激。

一个例子:

import React, {useEffect, Component} from 'react';
import api from '../../services/api'
import io from 'socket.io-client';
import './index.css'
export default class Home extends Component { 

    constructor(){
        super()

        this.state = {
          informationReceived: 'Nothing yet!',
          playerOne: 'Jogador 1',
          playerTwo: 'Jogador 2',
          socket: null
        }
        const token = localStorage.getItem('token');
        this.state.socket = io('http://localhost:8080', {
            query: { token: token }
        });
        var nome = prompt("Seu nome é:");
        this.state.socket.emit('adicionar-jogador', nome);
        this.state.socket.on('player conectado', (receivedInfo) => {
            this.setState({
              playerOne: receivedInfo[0].id,
              playerTwo: receivedInfo[1].id
            })
          });
        this.state.socket.on('fila', (receivedInfo) => {
            console.log('entrou')
            console.log(receivedInfo);
        });
      }


      emitInfoToAll = () => {
        const token = localStorage.getItem('token');
        console.log('entrou')
        const { socket } = this.state;

        socket.emit('myevent', 'Hello realtime connected users!')
        console.log(this.state.informationReceived);
      }
      render() {
        const { informationReceived } = this.state;
        const message = informationReceived;
        console.log(message);
    return (
        <div>
           <h1 id="resultado"></h1>
                <div id="player-1" className="user-panel">
                    <p>Nome: <span className="nome">{this.state.playerOne}</span></p>
                    <p>Pontos: <span className="pontos">0</span></p>
                    <div className="botoes">
                        <button onClick= {() => this.emitInfoToAll()} >Pedra</button>
                        <button>Papel</button>
                        <button>Tesoura</button>
                    </div>
                    <div className="jogada"></div>
                </div>

                <br />


                <br />
                <br />

                <div id="player-2" className="user-panel">
                <p>Nome: <span className="nome">{this.state.playerTwo}</span></p>
                    <p>Pontos: <span className="pontos">0</span></p>
                    <div className="botoes">
                        <button>Pedra</button>
                        <button>Papel</button>
                        <button>Tesoura</button>
                    </div>
                    <div className="jogada"></div>
                </div>

                <p id="espera"></p>  
    </div>
    );
    }
}

0 个答案:

没有答案