使用组合减速器时访问状态的其他部分 [英] Accessing other parts of the state, when using combined reducers

查看:21
本文介绍了使用组合减速器时访问状态的其他部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

注意:这是一个问题,非常类似于Redux;访问其他部分... 但是它与路由器无关:(因此不能以同样的方式解决

NB: This is a question, very similar to Redux; accessing other parts... but it has nothing to do with Router :( thus cannot be solved same way

当我减少状态的一部分时,我感觉"我还需要访问其他部分.我承认我可能误解"了 Redux 的核心原则,或者我的应用程序架构存在缺陷.

When I reduce one part of the state, I "feel" like I need to access other parts as well. I admit that I just might "misfeel" the core principals of the Redux, or have flaws in my app's architecture.

我目前的解决方案是修改 github:combineReducers.js的代码:

My current solution would be to modify github:combineReducers.js's code:

var finalState = mapValues(finalReducers, (reducer, key) => {
   var previousStateForKey = state[key]
   var nextStateForKey = reducer(previousStateForKey, action)
   ...
}

来自

   var nextStateForKey = reducer(previousStateForKey, action)

   var nextStateForKey = reducer(previousStateForKey, action, state)

这将允许我做我需要的事情:

which would allow me to do what I need:

function reducer(state, action, root) {
   if (root.otherPart.get("isSomething")) {
      return state.set("anotherThing", true);
   }
   return state;
}

问题是我的做法是否正确,还是应该使用不同的架构方法来解决,而无需从其他部分访问状态的一部分?

Question is if I am on the right way to do it, or is it something that should be solved using different architectural approaches, without having a need to access one part of state from other parts?

** 2018 年 12 月 5 日更新 **

由于对这个问题的兴趣相对较高(15 票赞成 atm),我在下面添加了我自己的答案,希望对那些正在寻找答案的人有所帮助.

Due to relatively high interest to this question (15 up-votes atm), I am adding my own answer below, hope it helps to those who is looking for that answer.

推荐答案

你不必使用combineReducers().

来自 官方 Redux 文档:

这个帮手只是为了方便!你可以自己写combineReducers 工作方式不同,甚至组合状态手动来自子减速器的对象并编写根减速器显式函数,就像您编写任何其他函数一样.

This helper is just a convenience! You can write your own combineReducers that works differently, or even assemble the state object from the child reducers manually and write a root reducing function explicitly, like you would write any other function.

您可以在 reducer 层次结构的任何级别调用 combineReducers.它不必发生在顶部.事实上,你可以再次使用它将过于复杂的子减速器拆分为独立的孙子孙女等等.

You may call combineReducers at any level of the reducer hierarchy. It doesn’t have to happen at the top. In fact you may use it again to split the child reducers that get too complicated into independent grandchildren, and so on.

所以你提出的解决方案绝对是你可以做到的一种方式.

So your proposed solution is definitely one way you can do it.

感谢@MichelleTilley 引领思路!

Thanks to @MichelleTilley for spearheading the train of thought!

这篇关于使用组合减速器时访问状态的其他部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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