如何同步 Redux 状态和 url 查询参数 [英] How to sync Redux state and url query params

查看:39
本文介绍了如何同步 Redux 状态和 url 查询参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有搜索面板的网页.搜索面板有几个输入字段:id、size、...

I have a web page with a search panel. Search panel has several input fields: id, size, ...

我想要的是当用户设置搜索值(例如:id=123 和 size=45)并按下搜索按钮时:

What I want is when user set search values (for example: id=123 and size=45) and press a search button:

  1. Redux reducer 中的 searchState 应该更新为新的搜索值(id=123 和 size=45)
  2. URL 应更改为http://mydomain/home?id=123&size=45"

另一方面,如果用户将 URL 更改为 http://mydomain/home?id=111&size=22 然后:

And on the other hand if the user changes URL to http://mydomain/home?id=111&size=22 then:

  1. reducer 中的 searchState 应该使用新的搜索值(id=111 和 size=22)进行更改
  2. UI 搜索面板输入应更新为新值(id=111 和 size=22)

如何达成目标?我应该使用什么路由器(react-router、redux-router、react-router-redux 或其他)?

How to reach with goal? What router should I use (react-router, redux-router, react-router-redux ot other)?

推荐答案

我建议直接使用 React Router在 Redux 中保留 searchState.React Router 会将 URL 参数注入到你的组件中,你可以在 mapStateToProps(state, ownProps) 中使用它们来计算最终的 props.

I would suggest just using React Router directly and not keeping searchState in Redux. React Router will inject URL parameters into your components, and you can use them in mapStateToProps(state, ownProps) to calculate the final props.

如果您真的想将路由更改视为操作,可以使用 react-router-redux 两个-way 同步,但它不会给你状态中的参数——只是当前位置.如果您想记录和重放操作,并在重放时更新 URL 栏,这是它的唯一用例.

If you really want to see route changes as actions, you can use react-router-redux for two-way syncing, but it won’t give you the params in the state—just the current location. The only use case for it if you want to record and replay actions, and have the URL bar update as you replay them.

这绝不是必需的——在大多数情况下,直接使用 React Router 就足够了.

It is by no means required—in most cases, just using React Router directly is enough.

这篇关于如何同步 Redux 状态和 url 查询参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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