来自 React 的 SignalR:'HubConnectionBuilder' 未定义 no-undef

SignalR from React: 'HubConnectionBuilder' is not defined no-undef

首先,我对 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;

在您使用 "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