我正在用React Native为.NET编写的后端构建一个移动应用程序。后端已使用SignalR集线器实现了实时消息传递服务。我正在使用软件包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);
})
}
答案 0 :(得分:0)
在使用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();
}