Data binding in reaction + signal

I have a strategic question.

I want to change the data on my website using signalR and display the changed data using a reaction. My question is: How do I bind data between the signal and respond?

My first clue is this:

signalR:

chat.client.addMessage = function (name, message) { chatHistory.push({ Author: name, Text: message }); //here I change global variable chatHistory }; 

react:

 var CommentList = React.createClass({some class here}); var CommentBox = React.createClass({ componentRefresh: function () { this.setState({ data: chatHistory }); }, getInitialState: function () { return { data: chatHistory }; }, componentDidMount: function () { this.componentRefresh(); setInterval(this.componentRefresh, this.props.interval); }, render: function () { return ( React.DOM.div(null, CommentList({ data: this.state.data }) ) ); } }); React.renderComponent( CommentBox({ interval: 2000 }), document.getElementById('content') ); 

in the response of the commentBox component I pass the global chat history and request a new value every 2 seconds.

Is there a more elegant way to do this? and how to avoid redrawing the CommentBox if the chatHistory variable has not been changed?

+6
source share
1 answer

Your approach to maintaining state in CommentBox is fine. As your component base grows, it can be difficult to maintain self-updating components. I recommend exploring the Flux architecture developed by the React team and their Todo MVC Flux example .

You can implement shouldComponentUpdate to prevent React from rendering the CommentBox again if you know that the state has not changed. In addition, you must maintain a link to this interval so that you can clear it when the CommentBox is disabled, otherwise it will continue to poll after the component has been removed.

 var CommentBox = React.createClass({ ... componentDidMount: function() { this.componentRefresh(); this._interval = setInterval(this.componentRefresh, this.props.interval); }, componentWillUnmount: function() { clearInterval(this._interval); this._interval = null; }, shouldComponentUpdate: function(nextProps, nextState) { // Do a deep comparison of `chatHistory`. For example, use // Underscore `isEqual` function. return !_.isEqual(this.state.chatHistory, nextState.chatHistory); }, ... }); 
+4
source

Source: https://habr.com/ru/post/973095/


All Articles