Redux:为什么不将动作和减速器放在同一个文件中? [英] Redux: Why not put actions and reducer in same file?

查看:19
本文介绍了Redux:为什么不将动作和减速器放在同一个文件中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Redux 创建一个应用程序,并且正在摸索为什么最好将操作和减速器放在单独的文件中.至少,这是我从所有例子中得到的印象.

I'm creating an app with Redux and am scratching my head as to why it is best to place actions and reducers in separate files. At least, that's the impression I'm getting from all the examples.

每个动作,或动作创建者,似乎都映射到一个由reducer调用的函数(在switch语句中).将它们放在同一个文件中不是合乎逻辑的吗?它还可以更轻松地为操作类型和切换案例使用相同的常量,因为它不必在文件之间导出/导入.

Each action, or action creator, appears to map to a single function that is called by a reducer (inside a switch statement). Wouldn't it be logical to keep these together in the same file? It also makes using the same constant for the action type and switch case easier, as it doesn't have to be exported/imported between files.

推荐答案

来自 Redux 创建者 Dan Abramov:

From Redux creator Dan Abramov:

许多减速器可以处理一个动作.一个减速器可以处理许多行动.将它们放在一起否定了 Flux 和Redux 应用程序规模.这会导致代码膨胀和不必要的耦合.你失去了对相同动作做出反应的灵活性不同的地方,你的动作创建者开始表现得像setter",耦合到特定的状态形状,从而耦合组件也是如此.

Many reducers may handle one action. One reducer may handle many actions. Putting them together negates many benefits of how Flux and Redux application scale. This leads to code bloat and unnecessary coupling. You lose the flexibility of reacting to the same action from different places, and your action creators start to act like "setters", coupled to a specific state shape, thus coupling the components to it as well.

来自 Redux 文档:

我们建议您编写独立的小型 reducer 函数,这些函数是每个负责更新特定状态片.我们称之为模式减速器组合".一个给定的动作可以被所有人处理,一些,或没有.这使组件与实际分离数据更改,因为一项操作可能会影响状态的不同部分树,组件不需要意识到这一点.

We suggest you write independent small reducer functions that are each responsible for updates to a specific slice of state. We call this pattern "reducer composition". A given action could be handled by all, some, or none of them. This keep components decoupled from the actual data changes, as one action may affect different parts of the state tree, and there is no need for the component to be aware of this.

请参阅 Twitter 上的此对话github 上的这个问题 了解更多信息.

See this conversation on twitter and this issue on github for more information.

这篇关于Redux:为什么不将动作和减速器放在同一个文件中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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