在匿名函数内调用react函数

Lui*_* E. 4 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();
  });
 });
},
Run Code Online (Sandbox Code Playgroud)

事实证明,addItem当消息到达时找不到.如何在anon函数中调用react方法?

dfs*_*fsq 12

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

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

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

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

最后,您还可以使用具有词法范围的ES2015 箭头函数:

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