在将react项目从17.0.2版升级到18.0.0版之后,我注意到了一些有趣的事情。
在我的应用程序的主页上,我使用WebSocket为SignalR打开一个连接。Resive17.0.2运行良好,但是升级到Reactive18.0.0之后,由于某种原因,WebSocket一直断开连接。在那之后,我又反应了17.0.2,问题就解决了。
我不太清楚为什么,我也找不到任何与这个话题有关的问题。
我所做的唯一的事情就是更新我的package.json以使用react和react-dom的版本18,然后在index.js中进行了必要的更改。
如果任何人在升级后有类似的问题作出反应18,一些信息将是有帮助的。
谢谢,同时我会做更多的研究,也许我能找出问题出在哪里。
更新问题似乎与包装我整个应用程序代码的<React.StrictMode>有关。
由于某些原因,在使用严格模式时,react会触发useEffect清理函数,该函数一旦离开页面,将WebSocket与HomePage断开连接。我已经删除了严格模式,现在它运行得很好(这只适用于react 18,如果我继续使用react 17和严格模式,我就没有这个“问题”)
有关React.StrictMode如何工作的更多信息:https://github.com/reactwg/react-18/discussions/19
发布于 2022-09-14 22:14:31
这意味着您的系统中有一个潜在的错误。用户应该能够离开负责设置hubconnection的组件导航,然后向后导航(这就是严格模式试图模拟的内容)。这就是我们正在做的事情(在自定义中间件中)
async init() {
this.connection = new HubConnectionBuilder()
.withUrl("url-to-your-hub", yourHubConfig)
.withAutomaticReconnect()
.build();
this.connection.start().then(() => {
this.connection?.on(HubClientMethod,
(message: HubMessage) => this.onSocketMessage(message));
if (this.shouldStopConnection) {
this.cleanUpConnection();
this.shouldStopConnection = false;
}
});
}
async cleanUpConnection() {
if (!this.connection) return;
if (this.connection.state === HubConnectionState.Connecting) {
this.shouldStopConnection = true;
return;
}
this.connection.off(HubClientMethod);
await this.connection.stop();
this.connection = null;
}https://stackoverflow.com/questions/71824076
复制相似问题