Redux - 在 reducer 中使用 action 对象方法而不是 switch

Redux - Use action object method in reducer instead of switch

我是 redux 的新手,看过 redux-actions 或在 reducer 中使用 switch 语句,虽然我不反对使用 switch 语句,但我想知道,使用调用动作方法?

这是我的想法

import actions from './actions'

const reducer = (state = {}, action) => {
   if (actions[action.type]) return Object.assign({},
       state, actions[action.type](action)
   );
   return state;
}

我刚刚在我的第一个 reducer 和 action 上测试了它,它可以工作,但它看起来很明显所以我想知道为什么选择开关类型?

一些观察:

  1. 不要将这些外部函数称为 "actions"。它们不是行动。它们本身就是减速器。
  2. 作为减速器,您确实应该将状态对象传递给它们。通常,您会 want/need 利用当前状态中包含的信息以及操作对象中包含的信息。

否则,这似乎是一种合适的方法。

Switch 语句当然是最常见的方法,但查找表也很常见。如果需要,您甚至可以使用简单的 if/then 条件。最终,如何编写 reducer 取决于您。

仅供参考,Redux FAQ, in the FAQ: Reducers section. You might also want to read the new "Structuring Reducers" 方法部分也介绍了该主题。