在匿名函数中调用React函数

5
我有一个在React组件中的函数,像这样:

我有一个在React组件中的函数,像这样

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。我该如何在匿名函数中调用React方法?
2个回答

13

最简单的解决方法是在某个变量中存储对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 箭头函数,它们具有词法作用域:

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接