Redux:为什么不把 actions 和 reducer 放在同一个文件中?

Redux: Why not put actions and reducer in same file?

我正在使用 Redux 创建一个应用程序,我绞尽脑汁想知道为什么最好将操作和缩减程序放在单独的文件中。至少,这是我从所有示例中得到的印象。

每个动作,或 动作创建者,似乎都映射到一个由 reducer 调用的函数(在 switch 语句中)。将它们放在同一个文件中不是合乎逻辑的吗?它还使对操作类型和开关大小写使用相同的常量变得更容易,因为它不必在文件之间是 exported/imported。

来自 Redux 的创造者 Dan Abramov:

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 docs

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.

有关详细信息,请参阅 this conversation on twitter and this issue on github

将 Actions 和 Reducers 保存在单独的文件中有助于保持代码模块化。

查找错误、扩展代码以及通常在尽可能小的部分上工作会更容易。

示例:

将 API 错误消息保存到 Redux 存储中可能会有所帮助。

如果我忘记使用其中一个 Reducer 上的传入错误更新存储,则可能很难跨多个文件找到它。

如果我在同一个文件中查看多个 Reducer,将更容易发现其中一个缺少 error: action.payload 行。

如果你愿意,请这样做。 否则说什么的人不知道你喜欢什么,不喜欢什么。凡是引用 Dan Abramov(一个优秀的开发人员)的人都是没脑子的羊。

现在 Redux 正式发布 redux-toolkit 以鼓励将它们保存在同一个文件中。它好多了,您将能够在一个文件中看到一个功能而不是多个。现在同样的人会开始称赞将它们保存在同一个文件中。

为了发出 POST 请求而更新类型、动作、缩减器、操作 (thunk/saga) 是一种可怕的开发体验。天生慢的人可以支持这样的事情,因为他们看不到影响。