在反应路由器中保持 websocket 连接 [英] Maintaining websocket connection in react router

查看:94
本文介绍了在反应路由器中保持 websocket 连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用 React Router 进行路由的 React/Redux 应用.

I have a React/Redux app using React Router for routing.

作为这个应用程序的一部分,我设置了一个 websocket 连接.我面临的一个问题是,当直接导航到 url 时,连接会断开.

As part of this app I set up a websocket connection. An issue I'm facing is that when navigating directly to a url, the connection is dropped.

例如:

  1. 用户登陆主页 www.app.com/
  2. Websocket 连接已建立.
  3. 用户通过 React Router browserHistory 导航到 www.app.com/link(此页面上没有建立任何连接的代码).
  4. 保持连接.
  1. User lands on home page at www.app.com/
  2. Websocket connection is established.
  3. User naviagtes to www.app.com/link via React Router browserHistory (there is no code to establish any connection on this page).
  4. Connection is maintained.

这按预期工作.但是:

  1. 用户登陆主页 www.app.com/
  2. Websocket 连接已建立.
  3. 用户通过在地址栏中输入它直接导航到 /link(或通过前面的示例导航到它后刷新页面.
  4. 连接中断.
  1. User lands on home page at www.app.com/
  2. Websocket connection is established.
  3. User navigates directly to /link by entering it in the address bar (or refreshing the page after navigating to it via previous example.
  4. Connection dropped.

这是预期的行为吗?如果是这样,是否有任何 Redux/React 路由器模式可以避免它?每次都要手动重新建立连接吗?

Is this expected behaviour? If so are there any Redux/React Router patterns for avoiding it? Do I have to manually re-establish the connection every time?

推荐答案

是的,这是预期的行为.当您刷新页面或通过键入 URL 手动导航时,浏览器将再次转到服务器以加载文件,包括您的 javascript 应用程序(它可能从缓存中获取,但结果是相同的).因此,您在内存中的 javascript 代码(包括 websocket 连接)将丢失,并且所有脚本都将被再次评估.

Yes, this is the expected behavior. When you refresh the page or navigate manually by typing the URL, the browser will go to the server again to load the files, including your javascript app (it may get it from the cache but the result is the same). Because of this your javascript code that is in memory, including the websocket connection, will be lost and all the scripts will be evaluated again.

没有办法解决这个问题.要始终打开 websocket 连接,您只需在应用入口点脚本中打开连接即可,无论用户在哪个页面.

There's no way around this. To always have a websocket connection open you can just open the connection in your app entry point script, regardless of what page the user is in.

这篇关于在反应路由器中保持 websocket 连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆