下面是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只出现在控制台上,而我对它进行setState,以便它显示在屏幕上。任何线索,如何去渲染数据?
编辑1:我漏掉了this后面的分号。设置状态({数据:websocket_data})
现在,点暂时显示,但由于:
getInitialState: function() {
return {data: []};
},
点消失。有人能帮我解决这个问题吗??
我发现了代码的问题。实际上,由于'POST' ajax调用失败,错误方法正在被调用,并且再次将数据设置为NULL。我注释掉了那一行,现在它工作得很好。
error: function (xhr, status, err) {
// this.setState({data: line});
console.error(url, status, err.toString());
}.bind(this)