为什么action会触发所有reducers

利用combineReducers组成的组合reducers,利用action触发,里面的每个reducers等都会触发?

阅读 2.4k
2 个回答

源码里每个reducer都会执行一遍 只会触发匹配到actionType

combineReducers源码大致是这样的:

/**
 * @params reducers 子reducer
 * @return nextState 返回更新之后的state
 **/
function combineReducers(reducers){
    const reducerKeys = Object.keys(reducers);

    return function combination(state = {}, action) {
        // This is the object we are going to return.
        const nextState = {}

        // Loop through all the reducer keys
        for (let i = 0; i < reducerKeys.length; i++) {
            // Get the current key name
            const key = reducerKeys[i];
            // Get the current reducer
            const reducer = reducers[key]
            // Get the the previous state
            const previousStateForKey = state[key]
            // Get the next state by running the reducer
            const nextStateForKey = reducer(previousStateForKey, action)
            // Update the new state for the current reducer
            nextState[key] = nextStateForKey;
        }
        return nextState;
    }
}

初始化combineReducers时,会遍历所有已传入的reduces对象的key,并将reducerKeys作为闭包变量存储在函数中,之后每次更新(dispatch动作)都只会循环这个数组和reducers对象的每个key。因为combination函数接受的参数state是更新后的庞大的对象,为了将每个子reduce返回更新后的state作为值添加并映射到nextState对象中对应key对象上,我们就需要调用每个reducer(previousStateForKey, action)

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题