我想在真实聊天中记录聊天记录。反应时

时间:2019-02-28 15:25:00

标签: reactjs websocket

我正在通过响应建立聊天网络。 他正在使用socket.io 获取数组中的值,并通过地图打印数据。 但是,与其保持以前获得的价值,不如将其更改为其他值。 我希望在价格保持不变并将值更改为另一个值时对新值盖章。

import React, { Component } from "react";
  import socketIOClient from "socket.io-client";
  import "./App.css";

  class App extends Component {
    constructor() {
      super();
      this.state = {
        endpoint: "http://xx.xxx.xxx.xxx:3000/",

        text: '',
        log: [

        ]
      };
    }

    handleChange = (e) => {
      this.setState({
        [e.target.name]: e.target.value
      })
    }


    send = () => {
      const socket = socketIOClient(this.state.endpoint);
      socket.emit('change color', this.state.text);
    }




    render() {


      const socket = socketIOClient(this.state.endpoint);
      socket.on('change color', (col) => {
        this.setState({
          log : col
        })
      })

      return (
          <div style={{ textAlign: "center" }}>


            <input placeholder={'입력칸'} type={'text'} name={'text'} onChange={this.handleChange}/>
            <button onClick={() => this.send()}>전송하기</button>
            <ul id={'log'}>
              {this.state.log.map((contact, i) => {
                return (<LogInfo name={contact.name} message={contact.message} key={i} />);
              })}
            </ul>
          </div>
      )
    }
  }

  class LogInfo extends React.Component {
    render() {
      return(
          <li>{this.props.name} {this.props.message}</li>
      );
    }
  }

  export default App;

响应为log:[message:foo]

1 个答案:

答案 0 :(得分:0)

当您收到change color事件时,您当前正在用收到的内容替换this.state.log,我想您想要的是将收到的内容添加到log数组中:< / p>

socket.on('change color', (col) => {
  this.setState({
    log: [
      ...this.state.log,
      col
    ]
  })
})

顺便说一下,您的代码段中有很多错误:

this.state = {
  endpoint: "http://xx.xxx.xxx.xx:3000/",
};

您的端点可能不应该处于您的状态,除非对其进行更改会触发组件的重新渲染。

您应该在构造函数中实例化一次套接字和套接字事件:

constructor () {
  this.socket = socketIOClient('http://xx.xxx.xxx.xx:3000/');
  this.socket.on('change color', () => {
    // Do something
  });
}

send = () => {
  this.socket.emit('change color', this.state.text);
}

,而不是每次都在渲染功能中使用。