简体   繁体   English

在匿名函数内调用react函数

[英]call react function inside anonymous function

I have a function inside a react component like this 我在这样的反应组件中有一个函数

addItem: function(data) {
    console.log(data)
    var oldMessages = this.state.messages;
    oldMessages.push({id: data.uid, content: data});

    this.setState({messages: oldMessages});
    this.scrollAndSetTimestamps()
    this.updateCount()
  },
componentDidMount: function() {
this.loadLatestMessages();
var socket = new SockJS('http://127.0.0.1:8080/stomp');
var stompClient = Stomp.over(socket);
stompClient.connect({}, function(frame) {
  // subscribe to the /room.uid endpoint
  stompClient.subscribe("/room.1247016", function(data) {
      var message = data.body;
      console.log("Received: "+message);
      this.addItem();
  });
 });
},

turns out that the addItem is not found when a message arrives. 事实证明,当消息到达时,找不到addItem How can I call a react method inside an anon function? 如何在anon函数中调用react方法?

The simplest solution is to store correct reference to this context in some variable: 最简单的解决方案是在某个变量中存储this上下文的正确引用:

var self = this;
stompClient.connect({}, function(frame) {
    stompClient.subscribe("/room.1247016", function(data) {
        var message = data.body;
        self.addItem();
    });
});

You could also use Function.prototype.bind , but this is not very readable: 您也可以使用Function.prototype.bind ,但这不是很易读:

stompClient.connect({}, function(frame) {
    stompClient.subscribe("/room.1247016", function(data) {
        var message = data.body;
        this.addItem();
    }.bind(this));
}.bind(this));

Finally, you could also go with ES2015 arrow functions which hold lexical scope: 最后,您还可以使用具有词法范围的ES2015 箭头函数

stompClient.connect({}, frame => {
    stompClient.subscribe("/room.1247016", data => {
        var message = data.body;
        this.addItem();
    });
});

I can not test your code truly, but I think it is because the js scope. 我无法真正测试你的代码,但我认为这是因为js范围。 where you call addItem, "this" is no longer point to the component,but the object which calls it. 在你调用addItem的地方,“this”不再指向组件,而是指向它的对象。 so, it you want to fix it, a reference method is relieve scope, the code like this: 所以,你要修复它,一个引用方法是缓解范围,代码如下:

componentDidMount: function() {
var _self = this;
_self.loadLatestMessages();
var socket = new SockJS('http://127.0.0.1:8080/stomp');
var stompClient = Stomp.over(socket);
stompClient.connect({}, function(frame) {
  // subscribe to the /room.uid endpoint
  stompClient.subscribe("/room.1247016", function(data) {
      var message = data.body;
      console.log("Received: "+message);
      _self.addItem();
  });
 });
},

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM