无法使用 @stomp/stompjs 订阅主题 [英] Unable to subscribe on topic using @stomp/stompjs
本文介绍了无法使用 @stomp/stompjs 订阅主题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的 React 组件的一部分:
Here is a part of my React component:
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();
}
...
根据浏览器控制台的调试输出,连接似乎已建立:
It looks like connection was established according to the debug output to browser's console:
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
从未被触发.
However, I don't see a message 'onConnect' in console, which means client.onConnect
was never fired.
因此我无法订阅主题.
这里可能有什么问题?
更新:
推荐答案
根据 编写它是库语法的混淆.
我的问题中更正后的代码如下所示:
The corrected code from my question look as the following:
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 中创建了一个完整的工作示例.
I created a full working example in my repo.
这篇关于无法使用 @stomp/stompjs 订阅主题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文