这是我的 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
从未被解雇。
因此我无法订阅主题。
这里可能有什么问题?
UPDATE:
根据作者认为这是一个混淆 https://github.com/stomp-js/stompjs/issues/18#issuecomment-432616031在库的语法中。
我的问题的更正代码如下所示:
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 https://github.com/akarasev/stomp-spring-react.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)