【发布时间】:2018-08-01 05:49:17
【问题描述】:
我有我的 Spring-Boot 服务设置,因此我可以通过 websocket 将消息发送到我的浏览器并且它可以工作。
//@MessageMapping
@RequestMapping(value = "/notify")
@SubscribeMapping("/notification")
@SendTo("/topic/notification")
public String sendNotification() throws Exception {
sendMessage();
return "Request to update Tanks has been sent!";
}
public void sendMessage() {
this.messagingTemplate.convertAndSend("/topic/notification", "IT WORKS");
}
这是来自 chrome 的控制台日志:
<<< MESSAGE
destination:/topic/notification
content-type:text/plain;charset=UTF-8
subscription:sub-1519225601109-13
message-id:f2qodiqn-8
content-length:8
IT WORKS
我希望能够从服务接收消息并更新响应中的状态,以便它从后端重新获取。这是我的客户的样子:
var socket = new SockJS("http://localhost:6667/refresh");
var stompClient = Stomp.over(socket);
stompClient.connect({}, function(frame) {
console.log('connected: ' + frame);
stompClient.subscribe('/topic/notification', function(notification){
console.log(notification.body);
//this.showNotification(JSON.parse(notification.body).content);
//this.showNotification(notification.body);
})
}, function(err) {
console.log('err', err);
});
还有componentDidMount()中的获取
fetch(`http://localhost:6666/front/objects`)
.then(result=>result.json())
.then(fuelTanks=>this.setState({fuelTanks}))
.catch(function(err) {
console.log('Could not fetch: ' + err.message);
}
)
我不能使用this.showNotification(notification.body),因此我不能将状态设置为能够重新获取我的对象。我尝试在类之外创建方法,但是我无法使用主类中的任何东西。
有没有办法让 react 再次运行 componentDidMount,或者更好的是,当我通过 websocket 从 spring 收到消息时访问我的类中的 fetch 方法?
像这样:
componentDidMount(){
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){
refetchTanks(); // call fetch tanks -> can't use "this"
})
}, function(err) {
console.log('err', err);
});
谢谢!
【问题讨论】:
-
您是否尝试在 stompClient.connect 方法中使用箭头函数进行回调?要么,要么您可以使用 this.refetchTanks = this.refetchTanks.bind(this); 将刷新坦克绑定到此。在组件的构造函数中
-
是的,我试过了。我得到了一个“未定义的属性 refetchTanks()”。我只是无法访问类方法。
-
你从哪里导入
SockJS?
标签: reactjs spring-boot websocket spring-websocket web-stomp