为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

至尊宝的传说 2023-09-07 14:35:53
我想在订阅块中调用方法,但我得到“无法读取未定义的属性‘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;  }
查看完整描述

1 回答

?
素胚勾勒不出你

TA贡献1827条经验 获得超9个赞

使用arrow函数来访问类成员,例如没有自变量的类的变量或方法。


尝试像下面这样


configureSocketChannel(senderId: string) {

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

    ws.connect({},  (frame) => {

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

        this.showMessageFromSocket(message);

      });

    }, function (error) {

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

    });

    this.wsObj = ws;

}


查看完整回答
反对 回复 2023-09-07
  • 1 回答
  • 0 关注
  • 46 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信