想要在React中渲染通过套接字接收的数据

时间:2016-08-09 07:06:40

标签: javascript reactjs websocket render

这是React代码:

var Dashboard = React.createClass({
  loadLineFromServer: function(line){
    console.log("inside loadlinefromserver");
    var socket = new WebSocket('ws://127.0.0.1:8000/');
    socket.onopen = function(){
      console.log("websocket opened");
      var send_data1 = "Point A: " + line.x1 + "," + line.y1 +" \n";
      var send_data2 = "Point B: " + line.x2 + "," + line.y2;
      socket.send(send_data1 + send_data2);
    }
    socket.onmessage = function(event){
      console.log("websocket on message");
      var websocket_data = event.data;
      this.setState({data: websocket_data})
      console.log(websocket_data);
    }.bind(this),
    socket.onerror = function(e){
      console.log("error in websocket");
      console.log(e.message);
    }
  },
  handleFormSubmit: function(line){
    this.loadLineFromServer({x1: line.x1, y1: line.y1, x2: line.y1, y2: line.y2});
    var url = util.format('http://127.0.0.1:8000/api/line/');
    $.ajax({
      url: url,
      crossDomain: true,
      dataType: 'json',
      data: line,
      type: 'POST',
      success: function (data) {
        this.setState({data: data});
      }.bind(this),
      error: function (xhr, status, err) {
        this.setState({data: line});
        console.error(url, status, err.toString());
      }.bind(this)
    });
  },
  getInitialState: function() {
    return {data: []};
  },
  componentWillMount: function() {
  },
  render: function(){
    return(
      <div className="dashboard">
        <Navbar inverse>
          <Navbar.Header>
            <Navbar.Brand>
              <a href="">TrainingInduct</a>
            </Navbar.Brand>
            <Navbar.Toggle/>
          </Navbar.Header>
        </Navbar>
        <Dashform onFormSubmit={this.handleFormSubmit} />
        <h1>{this.state.data}</h1>
      </div>
    );
  }
});

我找不到在屏幕上呈现的线坐标。 websocket_data只出现在控制台上,而我设置它以便它显示在屏幕上。关于如何渲染数据的任何线索?

Edit1:我错过了 this.setState({data:websocket_data})

之后的分号

现在,点数会暂时显示,但由于:

getInitialState: function() {
      return {data: []};
 },

积分。有人可以帮助解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

我发现了代码的问题。实际上由于'POST'ajax调用失败,错误方法被调用,并且再次将数据设置为NULL。我注释掉了那条线,现在它工作正常。

     error: function (xhr, status, err) {
     //  this.setState({data: line});
       console.error(url, status, err.toString());
     }.bind(this)