为什么我无法在订阅中调用方法 - 无法读取未定义的属性“showMessageFromSocket”

我想在订阅块中调用方法,但我得到“无法读取未定义的属性‘showMessageFromSocket’”。如何调用 showMessageFromSocket 方法?从角度来看这是可能的。


export default class ConnectedChatroom extends Component<

  ConnectedChatroomProps,

  ConnectedChatroomState

> {

  wsObj: CompatClient;


  constructor(props: Props, context: *) {

    super(props, context);

    this.configureSocketChannel('dassfa')

  }


  showMessageFromSocket(message)  {

    console.log(message);

    //do something

  }


  configureSocketChannel(senderId: string) {

    let ws = Stomp.client("ws://localhost:8080/chat");

    ws.connect({}, function (frame) {

      ws.subscribe("/topic/messages", function (message) {

        this.showMessageFromSocket(message);

      });

    }, function (error) {

      console.log("STOMP error " + error);

    });

    this.wsObj = ws;

  }


至尊宝的传说
浏览 49回答 1
1回答

素胚勾勒不出你

使用arrow函数来访问类成员,例如没有自变量的类的变量或方法。尝试像下面这样configureSocketChannel(senderId: string) {&nbsp; &nbsp; let ws = Stomp.client("ws://localhost:8080/chat");&nbsp; &nbsp; ws.connect({},&nbsp; (frame) => {&nbsp; &nbsp; &nbsp; ws.subscribe("/topic/messages",&nbsp; (message) => {&nbsp; &nbsp; &nbsp; &nbsp; this.showMessageFromSocket(message);&nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; }, function (error) {&nbsp; &nbsp; &nbsp; console.log("STOMP error " + error);&nbsp; &nbsp; });&nbsp; &nbsp; this.wsObj = ws;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript