【发布时间】:2022-10-04 20:34:11
【问题描述】:
我正在使用一个使用 React 作为前端和 .net 作为后端的应用程序。
现在我正在尝试将连接添加为一个数字,以向用户显示应用程序现在有多少人处于活动状态,我希望这个数字能够实时更新,我正在使用 SignalR。
发生的情况是当 1 个用户处于活动状态时,它显示 3 而不是显示 1。当 2 个用户处于活动状态时,它显示 6-7 并继续这样。
让我给你看一些代码
OnConnectionCountHub.cs
public class OnConnectionHub : Hub
{
public static int ConnectionCount { get; set; }
public override Task OnConnectedAsync()
{
ConnectionCount++;
Clients.All.SendAsync("updateConnectionCount", ConnectionCount).GetAwaiter().GetResult();
return base.OnConnectedAsync();
}
public override Task OnDisconnectedAsync(Exception? exception)
{
ConnectionCount--;
Clients.All.SendAsync("updateConnectionCount", ConnectionCount).GetAwaiter().GetResult();
return base.OnDisconnectedAsync(exception);
}
}
相当简单。
连接计数.tsx
export const ConnectionCount = () => {
const [connectionCount, setConnectionCount] = useState(0)
// create connection
useEffect(() => {
const connection = new HubConnectionBuilder()
.withUrl(urlOnConnectionHub)
.build()
// connect to method that hub invokes
connection.on("updateConnectionCount", (onConnection) => {
setConnectionCount(onConnection)
}
)
// start connection
connection.start().then(() => {
console.log("Connection started")
});
}, [])
return(
<section>
<p>Active users: {connectionCount}</p>
</section>
)
}
我的猜测是,因为这是一个组件,它在我使用该组件的地方获得了两倍的连接,而不是一个连接。
关于如何解决这个问题的任何想法? UseContext 可能吗?
【问题讨论】:
标签: c# reactjs asp.net-core signalr-hub react-tsx