【问题标题】:SignalR from React: 'HubConnectionBuilder' is not defined no-undef来自 React 的 SignalR:“HubConnectionBuilder”未定义 no-undef
【发布时间】:2020-05-25 16:10:10
【问题描述】:

首先,我对 JS 和 React 很陌生。我正在关注这个问题:How to import SignalR in React Component? 我想这是一件很简单的事情,但我不知道问题出在哪里。

错误:

Failed to compile.

./src/App.js
  Line 49:28:  'HubConnectionBuilder' is not defined  no-undef
  Line 52:28:  'JsonHubProtocol' is not defined       no-undef
  Line 53:25:  'LogLevel' is not defined              no-undef

我的 package.json:

  ...
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@aspnet/signalr": "^1.1.4",
  ...

我的 App.js

...
import * as signalR from '@aspnet/signalr';

class App extends React.Component {
  super(props);
  constructor(props) {
    this.connectionHub = "Endpoint=https://<signalrname>.service.signalr.net;AccessKey=<token>;Version=1.0;"
    this.accessToken = "<token>";

  ...

  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.accessToken,
    };

    // create the connection instance
    const connection = new HubConnectionBuilder()
      .withUrl(this.connectionHub, options)
      .withAutomaticReconnect()
      .withHubProtocol(new JsonHubProtocol())
      .configureLogging(LogLevel.Information)
      .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));
  }

  ...
}

export default App;

【问题讨论】:

    标签: reactjs signalr


    【解决方案1】:

    在您使用“HubConnectionBuilder”、“JsonHubProtocol”和“LogLevel”的所有地方,您必须将其用作:

    signalR.HubConnectionBuilder
    signalR.JsonHubProtocol
    signalR.LogLevel
    

    因为所有这些都是由@aspnet/signalr 库导出的。

    或者为了更好的方法,你可以替换

    import * as signalR from '@aspnet/signalr';
    

    import { HubConnectionBuilder, JsonHubProtocol, LogLevel } from '@aspnet/signalr';
    

    这样做你不需要每次都signalR.xyz

    【讨论】:

    • 谢谢@Parth!我还必须更改为`@microsoft/signalr` 而不是aspnet,以便它接受withAutomaticReconnect
    猜你喜欢
    • 2020-12-21
    • 2019-11-10
    • 2019-10-05
    • 2018-03-18
    • 2022-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-05
    相关资源
    最近更新 更多