为什么在Redux中单独执行动作+ reducers?

005*_*005 8 redux

我已经看到了分离行动和减少者的论点,因为他们有多对多的关系.

我不认为这实际上适用于Redux.因为只有1个数据存储区,所以对reducer的操作应该是1对多.

通常,reducer适用于特定数据存储的特​​定更改.

MY_ACTION = "MY_ACTION"
function reducer(state, action) {
    switch(action.type) {
        case MY_ACTION: // stuff with my action to create new state
        default: return state
    }
}
Run Code Online (Sandbox Code Playgroud)

我们可以组合多个reducer,combineReducers为什么不为动作本身定义动作的处理程序.

例如

class Action {
    constructor(type) {
        this.type = type
        this.handlers = []
    }
    add_handler(handler) {
        this.handlers += handler
    }
    get_reducer() {
        reducer = combineReducers(this.handlers)
        return (state, action) => {
            if(action.type == this.type) {
                return reducer(state, action)
            }
            return state
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

使用"ducks"模式,我们最终将主减速器放在与动作声明相同的模块中.

是否有任何理由将reducer + actions与redux分开?

And*_*ham 3

将动作创建者与减速器函数分离的主要原因是减速器函数必须是纯函数。如果您想在操作创建器中执行某些操作,例如异步 API 调用,那么您不能将其放入减速器中。这里有一个很好的解释。