javascript - 使用 aspnet/signalr 通过 React 访问 Signal R
问题描述
我正在使用下面的链接在 react 中实现 SignalR
但是,此代码似乎不符合当前标准,并且 @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 样本,现在有反应或知道如何做到这一点?
该软件包不会安装为过时的
保罗
解决方案
您可以创建自定义中间件,您不需要“需要” 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 });
});
推荐阅读
- android - Android:因为找不到 java 类而崩溃
- excel - 比较 2 个 excel 工作表并找到不在工作表 2 中的值
- google-colaboratory - 什么是谷歌 colab 功率级别?
- r - 如何在R中突出显示excel单元格
- c# - 如何从字符串中提取名称和版本
- javascript - 如何将图像旋转特定时间然后慢慢停止
- c++ - #ifdef x64 不适用于 windows 资源文件
- sql - sql中返回多行时如何选择只返回第一行
- c# - 如何在 html 字符串中将 http://localhost 替换为 ~/
- c# - 混合控制台/表单应用程序总是打开第二个控制台