简体   繁体   中英

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. How can I call a react method inside an anon function?

The simplest solution is to store correct reference to this context in some variable:

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:

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:

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. where you call addItem, "this" is no longer point to the component,but the object which calls it. 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();
  });
 });
},

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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