基本的 redux 概念——如何启动 reducers

fundamental redux concept- how to actions launch reducers

为了简单起见,请考虑这两个减速器(用打字稿编写):

export type userActionTypes = 
    | Interface1
    | Interface2

const initialState1 =  {...//some state} //<--comment indicates some sort of values are present
const initialState2 =  {...//some state}

const reducer1 = (state = initialState1, action: userActionTypes){
    switch(action.type) {
        case action1.case1:
            return {...//some new state1}
        default: return state
    }
}

const reducer2 = (state = initialState2, action: userActionTypes){
    switch(action.type){
        case action2.case2:
            return {...//some new state1}
        default: return state
    }
}

const rootReducer = combineReducers({
    mReducer1: reducer1,
    mReducer2: reducer2
})

现在说一下我们在代码中调用以下内容的地方:

newAction = {type: action2.type2, //some other values}
dispatch(newAction);

**我的问题是:** React 如何知道要调用哪个减速器? 我的意思是,它不会将操作传递给 rootReducer 中的每个减速器,是吗?我的意思是,如果是这种情况,那么所有默认情况都将毫无意义,并且 case 语句中的所有情况都必须是唯一的。这不可能吧?
React 如何知道要调用哪个 reducer?

How does react know which reducer to call? I mean, it doesn't pass the action to every reducer there is in the rootReducer, does it?

技巧问题,redux 实际上会调用 all 你的减速器。

考虑你的根减速器:

const rootReducer = combineReducers({
  mReducer1: reducer1,
  mReducer2: reducer2
})

这将创建一个 reducer 函数树。当一个动作被分派到 store 时,它​​调用根 reducer 并传递当前的 state 和当前的 action。 reducer 依次递归调用它们嵌套的组合 reducer,传递 stateaction 直到它们到达一个叶节点,您可以在该叶节点中点击一个 reducer 函数并计算它们的下一个状态。他们要么有一个案例要处理 action,要么有 return 默认案例,这只是他们当前的状态。递归返回,returning 每个下一个状态切片,在每个级别组合,直到你回到根减速器,return 是整个下一个状态对象。

I mean if that was the case, then all the default cases would be meaningless and all the cases in the case statements would have to be unique. That is not possible, is it?

请记住,每个 reducer 函数仅在 状态的一小部分上运行,而不是 整个 state 对象。减速器的默认情况是 return 它的当前状态值,因为它没有工作要做。 内的所有 reducer cases 一个 reducer 函数应该是唯一的。如果两个动作触发相同的状态更新,那么它们应该被分组

case "case1":
case "case13":
  // both cases apply the same update