With React, unidirectional threads are often the best way to do this. To achieve this, we must use an event emitter.
Get JSON from the server using websockets, SSE or polling (it doesn't matter). They must be in envelope format. This will be an example chat application.
{
"type": "new-message",
"payload": {
"from": "someone",
"to": "#some-channel",
"time": 1415844019196
}
}
When you receive this message from the server, you send it as an event.
var handleMessage = function(envelope){
myEventEmitter.emit(envelope.type, envelope.payload);
};
. , . ( ).
var MessageList = React.createClass({
componentDidMount: function(){
myEventEmitter.on('new-message', this.handleNewMessage);
},
handleNewMessage: function(message){
if (message.to === this.props.channel) {
this.setState({messages: this.state.messages.concat(message)});
}
},
componentWillUnmount: function(){
myEventEmitter.removeListener(this.handleNewMessage);
},
...
});
, "user-new-message". , handleMessage, , , .
( ) .
html , . AJAX , , .