下面是我的React组件的一部分:
import React from 'react';
import { Client } from '@stomp/stompjs';
class Balance extends React.Component {
componentDidMount() {
const client = new Client({
brokerURL: 'ws://localhost:8080/stomp',
debug: (str) => {
console.log(str);
},
});
client.onConnect(() => {
console.log('onConnect');
client.subscribe('/topic/balance', message => {
console.log(message);
})
});
client.activate();
}
...看起来,连接是根据到浏览器控制台的调试输出建立的:
Opening Web Socket...
Web Socket Opened...
>>> CONNECT
accept-version:1.0,1.1,1.2
heart-beat:10000,10000
Received data
<<< CONNECTED
heart-beat:0,0
version:1.2
content-length:0
connected to server undefined但是,我没有在控制台中看到“onConnect”消息,这意味着client.onConnect从未被触发。
因此,我不能订阅一个主题。
这里有什么问题吗?
更新:

发布于 2018-10-26 09:58:06
根据对作者来说,这是一种混淆。的语法库。
我问题中的更正代码如下所示:
import React from 'react';
import { Client } from '@stomp/stompjs';
class Balance extends React.Component {
componentDidMount() {
// The compat mode syntax is totally different, converting to v5 syntax
// Client is imported from '@stomp/stompjs'
this.client = new Client();
this.client.configure({
brokerURL: 'ws://localhost:8080/stomp',
onConnect: () => {
console.log('onConnect');
client.subscribe('/topic/balance', message => {
console.log(message);
})
},
// Helps during debugging, remove in production
debug: (str) => {
console.log(new Date(), str);
}
});
this.client.activate();
}
...我在存储库中创建了一个完整的工作示例。
https://stackoverflow.com/questions/52941127
复制相似问题