我有一个策略问题.
我想使用signalR更改我网站中的数据,并使用react显示更改的数据.我的问题是:如何在signalR和反应之间执行数据绑定?
我的第一个线索如下:
signalR:
chat.client.addMessage = function (name, message) {
chatHistory.push({ Author: name, Text: message }); //here I change global variable chatHistory
};
Run Code Online (Sandbox Code Playgroud)
反应:
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')
);
Run Code Online (Sandbox Code Playgroud)
在reactBoxBox组件中,我提供全局chatHistory并每2秒请求一个新值.
有更优雅的方式吗?如果没有更改chatHistory变量,如何避免重绘CommentBox?
您在 CommentBox 中维护状态的方法很好。随着组件库的增长,维护自我更新组件可能会变得复杂。我建议研究 React 团队设计的 Flux 架构,特别是他们的Todo MVC Flux示例。
如果您知道状态没有改变,您可以实现shouldComponentUpdate阻止 React 重新渲染 CommentBox。另外,您应该保留对间隔的引用,以便在卸载 CommentBox 时可以清除它,否则它将在组件被删除后继续轮询。
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's `isEqual` function.
return !_.isEqual(this.state.chatHistory, nextState.chatHistory);
},
...
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3773 次 |
| 最近记录: |