【问题标题】:Can't use "this" in stomp client subscribe - React不能在 stomp 客户端订阅中使用“this”-React
【发布时间】: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


【解决方案1】:

为了能够使用我的类方法和 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 之前创建一个变量,以便能够像这样var self = this; 访问this,然后在subscribe 之后访问self.update()

【讨论】:

    【解决方案2】:

    我知道,这是一个有点老的问题,但是由于每次搜索 stomp 问题时都会弹出它,所以我想回答它。在回调中访问 this 的方法是先将回调与 this 绑定,然后在回调中访问整个对象。 示例:

        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);
    

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

    【讨论】:

    • 感谢您抽出宝贵时间!我还没有考虑过将函数作为参数传递。
    • 我的代码是 stompClient.connect({}, (frame) => { console.log('Connected: ' + frame); stompClient.subscribe('/user/api/getChat', ( messageOutput) =>{ // this.connectCallBack.bind(this); console.log(JSON.parse(messageOutput.body).message); var mymessage =JSON.parse(messageOutput.body).message; this.state = {incomingchatMessage: [], chatMessages:[] } }); });但无法刷新它。怎么办?
    猜你喜欢
    • 1970-01-01
    • 2020-10-16
    • 2022-12-12
    • 1970-01-01
    • 1970-01-01
    • 2014-11-05
    • 1970-01-01
    • 2019-02-02
    • 1970-01-01
    相关资源
    最近更新 更多