Maintaining websocket connection in react router

2019-07-27 22:35发布

问题:

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.