不能使用"这个"在stomp客户端订阅 - React

时间:2018-02-21 15:20:09

标签: reactjs spring-boot websocket spring-websocket web-stomp

我有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,或者更好,当我从spring通过websocket获取消息时,只需访问我班级中的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);
  });

谢谢!

2 个答案:

答案 0 :(得分:0)

我尝试了一切能够在stompClient的.subscribe方法中使用我的类方法和状态。如果服务中断,我能够连接并重新连接,但它无法正常工作。

我决定使用有效的react-stomp。我可以在onMessage=...中使用类方法。这就是我的代码:

<SockJsClient 
  url = 'http://localhost:8610/refresh/'
  topics={['/topic/notification']} 
  onConnect={console.log("Connection established!")} 
  onDisconnect={console.log("Disconnected!")}
  onMessage={() => this.update()}  <------ this method performs a new GET 
                                           request
  debug= {true}
/> 

我还必须在服务器端以特定方式发送消息,因为我在发送字符串时收到JSON错误。

this.messagingTemplate.send("/topic/notification", "{"text":"text"}");

<<< MESSAGE
destination:/topic/notification
content-type:text/plain;charset=UTF-8
subscription:sub-0
message-id:aaylfxl4-1
content-length:49

{

  "text": "text"

}

它目前有效,但我很好奇是否还有其他更好的解决方案来解决这个问题。

编辑:一个更好的解决方案here!使用第一篇文章中的代码并在connect之前创建变量,以便能够像this一样访问var self = this;,然后在self.update()之后访问subscribe }!

答案 1 :(得分:0)

我知道,这是一个有点老的问题,但是由于每次您搜索“踩踏”问题时都会弹出,因此我想回答一下。在回调中访问此对象的方法是先将此对象与回调绑定,然后可以在回调中访问整个对象。 示例:

    connectCallBack(){
  this.setState({loading:false})

 }
 errorCallback=()=>{

 }

componentDidMount() {


axios.post('http://localhost:8080/subscribe', null, { params: {
deviceId
}})
.then(response => response.status)
.catch(err => console.warn(err));

const socket = new SockJS('http://localhost:8080/test');
const stompClient = Stomp.over(socket);

//stompClient.connect();
stompClient.connect( {}, this.connectCallBack, this.errorCallback);

如果看到上面的代码,则两个回调都可以访问此代码。