reactjs - ASP.NET Core 3.1 SignalR 不会偶尔向 React 应用程序返回数据
问题描述
我正在使用 ASP.NET Core 3.1 和 React.js 构建一个应用程序,但是当我使用 SignalR 时,我onconnectedasync
会向调用者返回可用锦标赛的列表。
问题是它工作了大约 5 次然后它停止了(只在前端显示微调器,我没有在控制台中获得一系列锦标赛)。
这是我的 ASP.NET Core SignalR 代码:
public class GameHub : Hub<IGameClient>
{
private readonly ITournamentsStore _tournamentsStore;
private readonly IMapper _mapper;
public GameHub(ITournamentsStore tournamentsStore, IMapper mapper)
{
_tournamentsStore = tournamentsStore;
_mapper = mapper;
}
public override async Task OnConnectedAsync()
{
await Groups.AddToGroupAsync(Context.ConnectionId, "Not playing");
var availableTournaments = _tournamentsStore.GetAvailableTournaments();
var availableTournamentsDto = _mapper.Map<List<TournamentDto>>(availableTournaments);
await Clients.Caller.ShowMainLobby(availableTournamentsDto);
await base.OnConnectedAsync();
}
}
反应代码:
import React, { useEffect, useState } from "react";
import { HubConnectionBuilder } from "@microsoft/signalr";
import Spinner from "../common/Spinner";
import MainLobby from "../gameParts/MainLobby";
import { connect } from "react-redux";
import { Redirect, useHistory } from "react-router";
const GamePage = ({ account }) => {
const history = useHistory();
const [conn, setConn] = useState(null);
const [screen, setScreen] = useState("");
const [tournaments, setTournaments] = useState(null);
useEffect(() => {
const newConn = new HubConnectionBuilder()
.withUrl("/gameHub")
.withAutomaticReconnect()
.build();
setConn(newConn);
}, []);
useEffect(() => {
if (conn) {
conn
.start()
.then((result) => {
console.log("Connected");
conn.on("ShowMainLobby", (tournaments) => {
setTournaments(tournaments);
console.log(tournaments);
setScreen("ShowMainLobby");
});
})
.catch((ex) => console.log("connection Failed: ", ex));
}
}, [conn]);
function returnToHomeMenu() {
console.log(conn);
conn.stop();
history.push("/");
console.log("disconnected");
}
return !account.user.loggedIn ? (
<Redirect to="/login" />
) : screen === "" ? (
<>
<Spinner text="Establishing Real Time Connection" />
</>
) : screen === "ShowMainLobby" ? (
<>
<MainLobby
tournaments={tournaments}
returnToHomeMenu={returnToHomeMenu}
/>
</>
) : (
<></>
);
};
function mapStateToProps(state) {
return {
account: state.account,
};
}
export default connect(mapStateToProps)(GamePage);
任何帮助表示赞赏!
解决方案
推荐阅读
- xml - 从 xmlns oracle 中提取值
- vue.js - 有没有办法在加载列表之前完全打开 v-dialog?
- c# - NuGet 更新,现在抛出 OpenTok: System.IO.FileLoadException: Could not load file or assembly JWT Version=2.0.0.0 on CreateSession
- javascript - 非法调用 window['document']['body']['append'] 函数
- jsp - Java Struts 1 HTTP 状态 500
- r - 使用另一个数据帧的行索引(条件)过滤数据帧并组合该行
- c++ - 用于 RSA PKCS#1(密钥生成)的 C++ 中的加密安全 RNG
- c - Ncurses 在不同的平台上给出不同的颜色
- tfs - 如何从 Visual Studio TFS 2019 中删除其他工作空间?
- javascript - 每次单击后更改容器中的所有 Div 颜色