-->

Extract React Router state in URL

2019-08-08 14:51发布

问题:

I'm using react-router and redux-simple-router in conjunction with server side rendering and when I navigate to a url like:

routeActions.push({ pathname: '/main', state: 'some_state'});

I want to be able to extract some_state from the request so I can render an initial redux state and send that back to the client. How do I extract the state from the request on the server side? Where does history and react-router put it?

This is particularly important for mobile because desktop, as I've tested, doesn't fire separate requests but mobile devices do which means the page reloads with a fresh initial state.

回答1:

state corresponds to state in the History API - it's associated with the current location, but it's only available on the client, so it's not suitable for passing along arbitrary data if your app needs to support server-side rendering.

If you want it to be available on the server, you would need to make it part of the URL. perhaps as a query string.

Aside: location state is useful in other ways in isomorphic/universal apps, such as passing around POSTed form data to be handled using an onEnter hook, or for passing form data and validation errors to use a redirect transition to respond by rendering an invalid form in the same scenario.