利用combineReducers组成的组合reducers,利用action触发,里面的每个reducers等都会触发?
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)
13 回答12.8k 阅读
7 回答1.9k 阅读
3 回答1.1k 阅读✓ 已解决
2 回答1.2k 阅读✓ 已解决
6 回答897 阅读✓ 已解决
4 回答1.6k 阅读
6 回答1.1k 阅读
源码里每个reducer都会执行一遍 只会触发匹配到actionType