【发布时间】:2018-08-05 21:08:20
【问题描述】:
我在 render() 中有这段代码,它打开一个 websocket 并连接到一个 Rest 服务。
return (
<div className="App">
<SockJsClient
url = 'http://localhost:8610/refresh/'
topics={['/topic/notification']}
onConnect={console.log("Connection established!")}
onDisconnect={console.log("Disconnected!")}
onMessage={(msg) => this.update()}
debug= {true}
/>
一切正常 - 这种方法的唯一问题是,当重新呈现 UI 时,应用程序会关闭 websocket 并再次重新打开它。没有任何中断,应用程序只是恢复,没有任何反应。
这个操作非常消耗资源吗?有没有办法告诉 react 不要重新渲染那部分代码?我应该担心吗?
this.update() 在我的state 中重新设置一个数组。
我知道shouldComponentUpdate() 是我需要的,但是我必须创建一个新组件来进行重新渲染,对吧?我很困惑。
谢谢!
编辑:这也有效(@zavjs 的解决方案更干净)
componentDidMount(){
var self = this; // use self to reference this
var socket = new SockJS("http://192.168.1.139:8610/refresh");
var stompClient = Stomp.over(socket);
stompClient.connect({}, function(frame,) {
console.log('connected: ' + frame);
stompClient.subscribe('/topic/notification', function(notification) {
self.update(); // here
})
}, function(err) {
console.log('err', err);
});
还有here's 更多关于此的信息!
【问题讨论】: