Mah*_*man 4 javascript jquery signalr reactjs
我已经使用create-react-app搭建了最初的react应用程序。
我的DashBoard组件:
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import $ from 'jquery';
import 'signalr';
class Dashboard extends Component {
constructor(props) {
super(props);
var connection = $.hubConnection('http://[address]:[port]');
var proxy = connection.createHubProxy('[hubname]');
// atempt connection, and handle errors
connection.start()
.done(function(){ console.log('Now connected, connection ID=' + connection.id); })
.fail(function(){ console.log('Could not connect'); });
}
render() {
return (...);
}
}
export default Dashboard;
Run Code Online (Sandbox Code Playgroud)
现在,我从SignalR收到以下错误,说未添加jQuery,但已在上一行中将其导入:
错误:找不到jQuery。请确保在SignalR客户端JavaScript文件之前引用jQuery。
如果我注释掉导入“ signalr”;jQuery正确加载,我可以访问$模块内部。为什么会这样?
xei*_*ton 21
这就是我们现在(2020 年)使用新包 @microsoft/signalr 执行此操作的方式。我们使用 Redux,但您不必使用 Redux 才能使用此方法。
如果您使用的是@microsoft/signalr 包而不是@aspnet/signalr,那么您可以通过这种方式进行设置。这是我们在 prod 中的工作代码:
import {
JsonHubProtocol,
HubConnectionState,
HubConnectionBuilder,
LogLevel
} from '@microsoft/signalr';
const isDev = process.env.NODE_ENV === 'development';
const startSignalRConnection = async connection => {
try {
await connection.start();
console.assert(connection.state === HubConnectionState.Connected);
console.log('SignalR connection established');
} catch (err) {
console.assert(connection.state === HubConnectionState.Disconnected);
console.error('SignalR Connection Error: ', err);
setTimeout(() => startSignalRConnection(connection), 5000);
}
};
// Set up a SignalR connection to the specified hub URL, and actionEventMap.
// actionEventMap should be an object mapping event names, to eventHandlers that will
// be dispatched with the message body.
export const setupSignalRConnection = (connectionHub, actionEventMap = {}, getAccessToken) => (dispatch, getState) => {
const options = {
logMessageContent: isDev,
logger: isDev ? LogLevel.Warning : LogLevel.Error,
accessTokenFactory: () => getAccessToken(getState())
};
// create the connection instance
// withAutomaticReconnect will automatically try to reconnect
// and generate a new socket connection if needed
const connection = new HubConnectionBuilder()
.withUrl(connectionHub, options)
.withAutomaticReconnect()
.withHubProtocol(new JsonHubProtocol())
.configureLogging(LogLevel.Information)
.build();
// Note: to keep the connection open the serverTimeout should be
// larger than the KeepAlive value that is set on the server
// keepAliveIntervalInMilliseconds default is 15000 and we are using default
// serverTimeoutInMilliseconds default is 30000 and we are using 60000 set below
connection.serverTimeoutInMilliseconds = 60000;
// re-establish the connection if connection dropped
connection.onclose(error => {
console.assert(connection.state === HubConnectionState.Disconnected);
console.log('Connection closed due to error. Try refreshing this page to restart the connection', error);
});
connection.onreconnecting(error => {
console.assert(connection.state === HubConnectionState.Reconnecting);
console.log('Connection lost due to error. Reconnecting.', error);
});
connection.onreconnected(connectionId => {
console.assert(connection.state === HubConnectionState.Connected);
console.log('Connection reestablished. Connected with connectionId', connectionId);
});
startSignalRConnection(connection);
connection.on('OnEvent', res => {
const eventHandler = actionEventMap[res.eventType];
eventHandler && dispatch(eventHandler(res));
});
return connection;
};
Run Code Online (Sandbox Code Playgroud)
然后你会像下面这样调用。请注意,这是一个伪代码。根据您的项目设置,您可能需要以不同的方式调用它。
import { setupSignalRConnection } from 'fileAbove.js';
const connectionHub = '/hub/service/url/events';
export const setupEventsHub = setupSignalRConnection(connectionHub, {
onMessageEvent: someMethod
}, getAccessToken);
export default () => dispatch => {
dispatch(setupEventsHub); // dispatch is coming from Redux
};
Run Code Online (Sandbox Code Playgroud)
让我知道它是否通过投票有所帮助。谢谢
更新:请注意,如果您在ReactJS应用程序中使用Redux,则以下解决方案不一定是最佳解决方案。最好将signalR实现为中间件。您可以在此处找到最佳答案。
如果您不使用Redux,或者您仍想在React组件中实现它,请继续阅读:对于使用最新版本的signalR(核心v2.1)的人们,因为jQuery不再是signalR的依赖项,您可以像这样导入:
import * as signalR from '@aspnet/signalr';
Run Code Online (Sandbox Code Playgroud)
然后像这样使用它:
signalR.HubConnectionBuilder()
Run Code Online (Sandbox Code Playgroud)
这是一个例子:
import React, { PureComponent } from 'react';
import { string } from 'prop-types';
import * as signalR from '@aspnet/signalr';
class SignalR extends PureComponent {
constructor (props) {
super(props);
this.connection = null;
this.onNotifReceived = this.onNotifReceived.bind(this);
}
componentDidMount () {
const protocol = new signalR.JsonHubProtocol();
const transport = signalR.HttpTransportType.WebSockets;
const options = {
transport,
logMessageContent: true,
logger: signalR.LogLevel.Trace,
accessTokenFactory: () => this.props.accessToken,
};
// create the connection instance
this.connection = new signalR.HubConnectionBuilder()
.withUrl(this.props.connectionHub, options)
.withHubProtocol(protocol)
.build();
this.connection.on('DatabaseOperation', this.onNotifReceived);
this.connection.on('DownloadSession', this.onNotifReceived);
this.connection.on('UploadSession', this.onNotifReceived);
this.connection.start()
.then(() => console.info('SignalR Connected'))
.catch(err => console.error('SignalR Connection Error: ', err));
}
componentWillUnmount () {
this.connection.stop();
}
onNotifReceived (res) {
console.info('Yayyyyy, I just received a notification!!!', res);
}
render () {
return <span />;
};
};
SignalR.propTypes = {
connectionHub: string.isRequired,
accessToken: string.isRequired
};
export default SignalR;
Run Code Online (Sandbox Code Playgroud)
我发现Signalr依赖于jQuery。由于某种原因import $ from 'jquery'没有设置window.jQuery。这就是为什么需要明确地做到这一点。
我这样解决了这个问题:
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import $ from 'jquery';
window.jQuery = $;
require('signalr');
class Dashboard extends Component {
// .....
}
export default Dashboard;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5167 次 |
| 最近记录: |