如何同步 Redux 状态和 url 查询参数

编程入门 行业动态 更新时间:2024-10-20 20:35:30
本文介绍了如何同步 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:

  • Redux reducer 中的 searchState 应该更新为新的搜索值(id=123 和 size=45)
  • URL 应更改为mydomain/home?id=123&size=45"
  • 另一方面,如果用户将 URL 更改为 mydomain/home?id=111&size=22 然后:

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

  • reducer 中的 searchState 应该使用新的搜索值(id=111 和 size=22)进行更改
  • 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 查询参数

    本文发布于:2023-10-26 23:38:41,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1531677.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:状态   参数   Redux   url

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!