在匿名函数内调用react函数

时间:2015-12-31 18:01:52

标签: javascript reactjs

我在这样的反应组件中有一个函数

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();
  });
 });
},

证明,当邮件到达时找不到addItem。如何在anon函数中调用react方法?

2 个答案:

答案 0 :(得分:12)

最简单的解决方案是在某个变量中存储对this上下文的正确引用:

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

您也可以使用Function.prototype.bind,但这不是非常易读:

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

最后,你也可以选择具有词汇范围的ES2015 arrow functions

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

答案 1 :(得分:1)

我无法真正测试您的代码, 但我认为这是因为js的范围。 在你调用addItem的地方,“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();
  });
 });
},