这是我的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
。
因此,我无法订阅主题。
这可能是个问题吗?
答案 0 :(得分:0)
使用to author it was a mix up的库语法。
我的问题中纠正的代码如下:
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();
}
...
我在repo中创建了一个完整的示例。