如何在 React Component 中导入 SignalR?

新手上路,请多包涵

我已经使用 create-react-app 来构建初始的 React 应用程序。

我的 仪表板 组件:

 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;

现在我从 SignalR 得到以下错误,说没有添加 jQuery,但我已经在上面的行中导入了它:

错误:未找到 jQuery。请确保在 SignalR 客户端 JavaScript 文件之前引用 jQuery。

如果我注释掉 import “signalr”; jQuery 被正确加载,我可以访问模块内部的 $ 。为什么会这样?

原文由 Mahbubur Rahman 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 443
1 个回答

这就是我们现在(2020 年)使用新包@microsoft/signalr 的方式。我们使用 Redux,但您不必使用 Redux 也能使用此方法。

如果您使用的是@microsoft/signalr 包而不是@aspnet/signalr,那么您可以这样设置它。这是我们在产品中的工作代码:

 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;
};

然后你会像下面这样打电话。请注意,这是一个伪代码。根据您的项目设置,您可能必须以不同的方式调用它。

 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
};

让我知道它是否通过投票有所帮助。谢谢

原文由 xeiton 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题