在 URL 中提取 React Router 状态 [英] Extract React Router state in URL

查看:54
本文介绍了在 URL 中提取 React Router 状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将 react-router 和 redux-simple-router 与服务器端渲染结合使用,当我导航到如下网址时:

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'});

我希望能够从请求中提取 some_state 以便我可以呈现初始 redux 状态并将其发送回客户端.如何从服务器端的请求中提取状态?history 和 react-router 把它放在哪里了?

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.

推荐答案

state 对应于 History API 中的状态 - 它与当前位置相关联,但仅在客户端可用,因此如果您的应用需要,它不适合传递任意数据支持服务端渲染.

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.

如果您希望它在服务器上可用,则需要将其作为 URL 的一部分.也许作为查询字符串.

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.

旁白:位置状态在同构/通用应用程序中以其他方式很有用,例如传递要使用 onEnter 钩子处理的 POSTed 表单数据,或用于传递表单数据和验证错误以使用重定向转换在同一场景中通过呈现无效表单来响应.

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.

这篇关于在 URL 中提取 React Router 状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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