首页 > 解决方案 > 使用 aspnet/signalr 通过 React 访问 Signal R

问题描述

我正在使用下面的链接在 react 中实现 SignalR

ASP NET Core Signal R 教程

但是,此代码似乎不符合当前标准,并且 @aspnet/signalr-client 现在已被标记为已过时,并显示一条消息说必须使用 @aspnet/signalr

我设法弄清楚创建集线器连接的公认方式是

// create the connection instance
var hubConnection = new signalR.HubConnectionBuilder()
  .withUrl("URL", options)
  .withHubProtocol(protocol)
  .build();

但是,我不知道如何在反应中调用它?

我试过了

import signalR, {} from '@aspnet/signalr';

但这给出了错误

./src/components/widgets/Chat.js
Attempted import error: '@aspnet/signalr' does not contain a default export (imported as 'signalR').

有没有人有一个更新的 Signal R 样本,现在有反应或知道如何做到这一点?

该软件包不会安装为过时的

保罗

标签: javascriptreactjssignalr

解决方案


您可以创建自定义中间件,您不需要“需要” websockets 本身`这是我当前的应用程序:

配置商店.js:

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

//to server
export default function configureStore(history, initialState) {
const middleware = [
    thunk,
    routerMiddleware(history),
    SignalrInvokeMiddleware
];

const rootReducer = combineReducers({
    ...reducers,
    router: connectRouter(history)
});

const enhancers = [];
const windowIfDefined = typeof window === 'undefined' ? null : window;
if (windowIfDefined && windowIfDefined.__REDUX_DEVTOOLS_EXTENSION__) {
    enhancers.push(windowIfDefined.__REDUX_DEVTOOLS_EXTENSION__());
}

return createStore(
    rootReducer,
    initialState,
    compose(applyMiddleware(...middleware), ...enhancers)
);
}

const connection = new SignalR.HubConnectionBuilder()
    .withUrl("/notificationHub")
    .configureLogging(SignalR.LogLevel.Information)
    .build();

//from server
export function SignalrInvokeMiddleware(store, callback) {
return (next) => (action) => {
    switch (action.type) {
        case "SIGNALR_GET_CONNECTIONID":
            const user = JSON.parse(localStorage.getItem('user'));
            connection.invoke('getConnectionId', user.userid)
                .then(conid => action.callback());
            break;
        case "SIGNALR_USER_JOIN_REQUEST":
            let args = action.joinRequest;
            connection.invoke('userJoinRequest', args.clubId, args.userId);
            break;
        default:
    }
    return next(action);
}}

export function signalrRegisterCommands(store, callback) {
connection.on('NotifyUserJoinRequest', data => {
    store.dispatch({ type: 'SIGNALR_NOTIFY_USERJOIN_REQUEST', notification: data });
})

connection.start()
    .then(() => {
        callback();
    })
    .catch(err => console.error('SignalR Connection Error: ', err));
}

index.jsx:

const store = configureStore(history);
const callback = () => {
    console.log('SignalR user added to group');
}
signalrRegisterCommands(store, () => {
    console.log('SignalR Connected');
    store.dispatch({ type: 'SIGNALR_GET_CONNECTIONID', callback });
});

推荐阅读