Maintaining websocket connection in react router

ε祈祈猫儿з 提交于 2019-12-24 08:39:55

问题


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

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.

For example:

  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.

This works as expected. However:

  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.

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?


回答1:


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.

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.



来源:https://stackoverflow.com/questions/42222616/maintaining-websocket-connection-in-react-router

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!