简体   繁体   English

React / Redux-链接动作或合并减速器

[英]React/Redux - Chaining Actions or combining reducers

I am starting to learn React/Redux to build an app. 我开始学习React / Redux来构建应用程序。 I am trying to determine what best practice is for this situation. 我正在尝试确定这种情况下的最佳实践。 I (currently) have three pieces of state in Redux: 我(当前)在Redux中具有三种状态:

  1. A list of filter objects the user specifies 用户指定的过滤器对象列表
  2. State #1 is passed to an API call that processes it and returns a list of destinations 状态#1传递给API调用,该API对其进行处理并返回目的地列表
  3. A third list of buildings that is filtered down by #1 and #2 and is displayed to the user. 由#1和#2过滤并向用户显示的建筑物的第三列表。

So right now when a user changes the filter object, it calls an action that updates #1. 因此,当用户更改过滤器对象时,它会调用一个更新#1的动作。 However, the list of destinations depends on what the user specifies in #1. 但是,目的地列表取决于用户在#1中指定的内容。 My first thought is to let the action flow into a reducer - and then when the #1 object is built, call another action inside the reducer to build #2, which flows through its own reducer. 我的第一个想法是让动作流到化简器中,然后在构建#1对象时,调用化简器中的另一个动作来构建#2,它通过它自己的化简器流动。

This instinctively seems...bad. 这本能地看起来...不好。 My second thought was to combine #1 and #2 into one object that simply contains both states, process it in a single reducer and store it in Redux as a single piece. 我的第二个想法是将#1和#2组合到一个仅包含两个状态的对象中,在单个化简器中对其进行处理,并将其作为一个整体存储在Redux中。

What is considered best practice in this situation? 在这种情况下,什么是最佳做法?

I think dispatching an action from your reducer breaks unidirectional data flow principle, so best to take that off the table. 我认为从您的reducer调度动作会破坏单向数据流原理,因此最好将其移开表。

Your second approach sounds like good practice but it also depends on how easily state #3 needs to access #1 and #2, and if you're thinking about scalability, it might be best to leave all three as same-level siblings in the state tree. 您的第二种方法听起来像是一种好的做法,但它还取决于状态#3需要访问#1和#2的难易程度,并且如果您正在考虑可伸缩性,则最好将这三个都保留为同级兄弟。状态树。

To achieve this, create one action such as RECEIVE_DATA which might look like this: 为此,请创建一个类似于RECEIVE_DATA动作,如下所示:

{
  type: 'RECEIVE_DATA',
  payload: { /* data from API */ },
  meta: {
    filter: [ /* filter tags */ ]
  }
}

Use an action creator that makes the (async) call to the API. 使用动作创建者对API进行(异步)调用。 On success, dispatch RECEIVE_DATA and you should have two reducers both listening for RECEIVE_DATA . 成功后,调度RECEIVE_DATA ,您应该有两个减速器都在监听RECEIVE_DATA

One reducer is concerned with state #1 and the other is concerned with #2. 一个reducer与状态#1有关,另一个与#2有关。 They simply subscribe to the part of the state tree they're concerned with and you can return just the action.payload from one and action.meta.filter from the other. 他们只订阅状态树中与之相关的部分,就可以只返回其中一个的action.payload ,而另一个返回action.meta.filter

I suggest 'payload' and 'meta' just to be FSA compliant . 我建议“有效载荷”和“元”只是为了符合FSA

Hope that helps! 希望有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM