我正在尝试使用react和SignalR构建一个聊天应用程序。我试图编辑以下代码。
import * as React from 'react';
import { HubConnection, HubConnectionBuilder } from '@aspnet/signalr';
import * as signalR from '@aspnet/signalr';
class Chat extends React.Component {
constructor() {
super();
this.state = {
nick: '',
message: '',
messages: [],
hubConnection: null,
};
}
componentDidMount = () => {
const nick = window.prompt('Your name:', 'John');
//const hubConnection = new HubConnection('http://localhost:5000/chat');
//Said deprecated
const hubConnection = new HubConnectionBuilder().withUrl('http://localhost:5000/chat').build();
this.setState({ hubConnection, nick }, () => {
this.state.hubConnection
.start()
.then(() => console.log('Connection started!'))
.catch(err => console.log('Error while establishing connection :('));
this.state.hubConnection.on('sendToAll', (nick, receivedMessage) => {
const text = `${nick}: ${receivedMessage}`;
const messages = this.state.messages.concat([text]);
this.setState({ messages });
});
});
}
sendMessage = () => {
this.state.hubConnection
.invoke('sendToAll', this.state.nick, this.state.message)
.catch(err => console.error(err));
this.setState({ message: '' });
};
render() {
return (
<div>
<br />
<input
type="text"
value={this.state.message}
onChange={e => this.setState({ message: e.target.value })}
/>
<button onClick={this.sendMessage}>Send</button>
<div>
{this.state.messages.map((message, index) => (
<span style={{ display: 'block' }} key={index}> {message} </span>
))}
</div>
</div>
);
}
}
export default Chat;
我遇到的第一个问题是const hubConnection = new HubConnection('https://flutter.io/testing/');似乎已被弃用。
以下是我收到的一些错误。 有人可以让我知道一个新近更新的帖子,我可以参考它来构建此帖子。我没找到。
如果我不使用SignalR,还可以参考React来实现聊天可见性
答案 0 :(得分:0)
您可以从SignalR(v1.0.4)导入特定模块:
import {
JsonHubProtocol,
HttpTransportType,
HubConnectionBuilder,
LogLevel
} from '@aspnet/signalr'; // version 1.0.4
这是创建集线器的方法:
// create the connection instance
const connection = new HubConnectionBuilder()
.withUrl(connectionHub, options)
.withHubProtocol(protocol)
.build();
我希望能有所帮助。 here