【问题标题】:SignalR listener not getting invoked in React NativeSignalR 侦听器未在 React Native 中被调用
【发布时间】:2019-03-02 23:30:27
【问题描述】:

我正在用 React Native 为用 .NET 编写的后端构建一个移动应用程序。后端使用 SignalR Hub 实现了实时消息传递服务。我正在使用包react-native-signalr。连接正在建立,我可以通过调用proxy.invoke 向 SignalR 集线器发送消息。问题在于接收消息。我尝试使用proxy.on,但没有任何反应。

componentDidMount(){
  const { access_token } = this.props;

  // Setup connection to signalr hub.
  const hubUrl = `${API_URL}/signalr`;
  const connection = signalr.hubConnection(hubUrl);
  const proxy = connection.createHubProxy('MessagesHub', {queryParams: { token: access_token }});

  // Start connection
  connection.start();

  // Trying to receive message from SignalR Hub
  proxy.on('messageReceived', message => {
    console.log(message);
  })
  proxy.on('sendPrivateMessage', message => {
    console.log(message);
  })
  proxy.on('sentPrivateMessage', message => {
    console.log(message);
  })
}

【问题讨论】:

  • 你能导航到你的 huburl/signalr/negotiate 吗?
  • @xSkrappy 信号器/协商的响应{"Url":"/API/signalr","ConnectionToken":"zel8uzcmSs6Tenu+jpDcYNRcj/8KeTlV+00LQIzeFdgD/TdjeXXeyHRLvknybDJ0ruKDKttcipS6l2wrsawUEwscjMVENEFMMdCbtO4MrFrYjIJrePwxGs9BPWDBSI56QphwBgI1JeVSysr5HSw7GQ==","ConnectionId":"a166558f-0046-450d-b7d3-4ff25a57a636","KeepAliveTimeout":20.0,"DisconnectTimeout":30.0,"ConnectionTimeout":110.0,"TryWebSockets":false,"ProtocolVersion":"1.2","TransportConnectTimeout":5.0,"LongPollDelay":0.0}
  • 尝试把proxy.on放在connection.start()上面
  • @xSkrappy 我试过了。但是什么也没发生。

标签: react-native signalr signalr-hub


【解决方案1】:

当你用 your_proxy.on 函数注册监听器时,你必须定义一个带有所需参数的函数并将它绑定到构造函数上,然后将它传递给 your_proxy.on 函数,见下文:

constructor(props){
        super(props);
        this.messageReceived=this.messageReceived.bind(this);   // <========== **Important**
        this.sendPrivateMessage=this.sendPrivateMessage.bind(this);   // <========== **Important**
        this.sentPrivateMessage=this.sentPrivateMessage.bind(this);   // <========== **Important**
    }

messageReceived(message ){
             console.log(message);
    }
    sendPrivateMessage(message ){
             console.log(message);
    }
    sentPrivateMessage(message ){
             console.log(message);
    }
componentDidMount(){
  const { access_token } = this.props;

  // Setup connection to signalr hub.
  const hubUrl = `${API_URL}/signalr`;
  const connection = signalr.hubConnection(hubUrl);
  const proxy = connection.createHubProxy('MessagesHub', {queryParams: { token: access_token }});

// Trying to receive message from SignalR Hub
  proxy.on('messageReceived', this.messageReceived);
  proxy.on('sendPrivateMessage', this.sendPrivateMessage);
  proxy.on('sentPrivateMessage', this.sentPrivateMessage);

  // Start connection
  connection.start();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-30
    • 2020-08-26
    • 2019-07-25
    • 2019-01-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多