如何在React Component中导入SignalR? [英] How to import SignalR in React Component?

查看:753
本文介绍了如何在React Component中导入SignalR?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用 create-react-app 来构架最初的react应用程序.

I have used create-react-app to scaffold the initial react application.

我的 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;

现在我从SignalR收到以下错误,说未添加jQuery,但我已在上面的行中将其导入:

Now I get the below error from SignalR saying jQuery is not added, but I have imported it in the line above:

错误:找不到jQuery.请确保之前已引用jQuery SignalR客户端JavaScript文件.

Error: jQuery was not found. Please ensure jQuery is referenced before the SignalR client JavaScript file.

如果我注释掉导入"signalr"; jQuery正确加载,我可以访问模块内部的$.为什么会这样?

If I comment out import "signalr"; jQuery gets loaded correctly and i can access the $ inside the module. Why does this happen?

推荐答案

更新:请注意,如果您在ReactJS应用中使用Redux,则以下解决方案不一定是最佳解决方案. 最好将signalR实现为中间件.您可以在此处找到最佳答案.

UPDATE: Please note that if you are using Redux in your ReactJS app, the solution below is not necessarily the best solution. It is better to implement signalR as a middleware. You can find the best answer here.

如果您不使用Redux,或者您仍想在React组件中实现它,请继续阅读: 对于使用最新版本的signalR(核心v2.1)的用户,由于jQuery不再是signalR的依赖项,因此可以将其导入,例如:

If you are not using Redux, or you still want to implement it in a React component, then read on: For people that are using the latest version of signalR (core v2.1), since jQuery is not a dependency of signalR any more, you can import it like:

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

注意:现在有可用的新版本Signalr(@ microsoft/signalr),需要进行不同的设置.此解决方案仅适用于@ aspnet/signalr. ( 2020年6月更新)

NOTE: there is now a newer version of signalr available (@microsoft/signalr) that requires a different setup. This solution only works with @aspnet/signalr. (UPDATE June 2020)

然后像这样使用它:

signalR.HubConnectionBuilder()

这里是一个例子:

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;

更新:在2020年,您可以使用"withAutomaticReconnect()":

UPDATE: in 2020, you can use "withAutomaticReconnect()":

  const connection = new HubConnectionBuilder()
    .withUrl(connectionHub, options)
    .withAutomaticReconnect()
    .withHubProtocol(new JsonHubProtocol())
    .configureLogging(LogLevel.Information)
    .build();

这篇关于如何在React Component中导入SignalR?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆