Redux 在 reducer 之间共享动作 vs 触发多个动作

Redux Sharing action between reducers vs triggering multiple actions

例如,如果我有一个登录缩减器和一个用户图标缩减器。当我登录时,我想更新用户图标以及存储用户信息。我被困在两个选择之间:

第一个是导出 USER_LOGIN 操作并让登录缩减器和用户图标缩减器处理 USER_LOGIN 操作。

第二种方法是在 action 和 reducer 之间建立一对一的映射(一种类型的 action 只属于一个 reducer)。我们有登录缩减器句柄 USER_LOGIN,然后使用 Saga/Thunk 我们将副作用 UPDATE_USER_ICON 发送到用户图标缩减器。

哪种做法更好?我个人更喜欢第二种方法。

我会说你的第一种方法更好,这是我常用的方法。是的,当多个 reducer 作用于相同的 action 类型时,它可能会影响代码的可读性,但它有助于减少代码的冗长(这是我对 React 生态系统的主要抱怨)和一些性能。像登录这样的操作不会对性能产生巨大影响,但是当我对用户操作进行 API 调用时,我只是在多个 reducer 中处理相同的操作类型。为了便于阅读,我添加了注释和文档。

引用Redux FAQ entry on dispatching multiple actions

There's no specific rule for how you should structure your actions. Using an async middleware like Redux Thunk certainly enables scenarios such as dispatching multiple distinct but related actions in a row, dispatching actions to represent progression of an AJAX request, dispatching actions conditionally based on state, or even dispatching an action and checking the updated state immediately afterwards.

In general, ask if these actions are related but independent, or should actually be represented as one action. Do what makes sense for your own situation but try to balance the readability of reducers with readability of the action log. For example, an action that includes the whole new state tree would make your reducer a one-liner, but the downside is now you have no history of why the changes are happening, so debugging gets really difficult. On the other hand, if you emit actions in a loop to keep them granular, it's a sign that you might want to introduce a new action type that is handled in a different way.

Try to avoid dispatching several times synchronously in a row in the places where you're concerned about performance. There are a number of addons and approaches that can batch up dispatches as well.

你真的需要在 Redux 中存储用户图标吗?在这种情况下,更好的方法是让选择器 returns 基于登录用户的图标。这样你就可以在商店中保持最少的状态。

您可以使用 Reselect 库来缓存选择器。