美文网首页工作生活
Redux源码(五) —— combineReducers.js

Redux源码(五) —— combineReducers.js

作者: Xiaobo2020 | 来源:发表于2019-07-03 18:35 被阅读0次

Source Time

export default function combineReducers(reducers) {
  const reducerKeys = Object.keys(reducers)
  const finalReducers = {}
  // ... 过滤无效key,有效的添加到finalReducers上
  const finalReducerKeys = Object.keys(finalReducers)
  // ... 创建异常stateKey缓存对象
  // ... 错误断言
  return function combination(state = {}, action) {
    // ... 有错误断言处理错误断言
    // ... 非生产环境获取异常state警告信息,并弹出警告
    let hasChanged = false
    const nextState = {}
    for (let i = 0; i < finalReducerKeys.length; i++) {
      const key = finalReducerKeys[i]
      const reducer = finalReducers[key]
      const previousStateForKey = state[key]
      const nextStateForKey = reducer(previousStateForKey, action)
      // ... 处理返回state为undefined的错误信息
      nextState[key] = nextStateForKey
      hasChanged = hasChanged || nextStateForKey !== previousStateForKey
    }
    return hasChanged ? nextState : state
  }
}

Analysis

combineReducers接受一个reducers对象,并返回一个combination统一处理dispatch触发的action操作。在combineReducers中会进行过滤无效reducer、处理reducer返回undefined无效结果等情况,最终得到一个包含了有效子reducer的finalReducer对象以及由此衍生得到的finalReducerKeys数组。

在新的可以理解为rootReducer——combination中,会根据finalReducerKeys数组遍历finalReducer对象,对每一个可能存在的子reducer都运行一次获取到对应的nextStateForKey值,最后合并到nextState上,而每一次得到的新nextStateForKey都会与之前的previousStateForKey比较,用于判断combination是直接返回原始state还是返回新得到的nextState

Example

为了方便理解,可以看个简单的例子

const theDefaultReducer = (state = 0, action) => state;
const firstNamedReducer = (state = 1, action) => state;
const secondNamedReducer = (state = 2, action) => state;
const rootReducer = combineReducers({
  theDefaultReducer,
  firstNamedReducer,
  secondNamedReducer
});
const store = createStore(rootReducer);
console.log(store.getState());
// -> {theDefaultReducer: 0, firstNamedReducer: 1, secondNameReducer: 2}

All

index
compose
applyMiddleware
bindActionCreators
combineReducers
createStore

相关文章

网友评论

    本文标题:Redux源码(五) —— combineReducers.js

    本文链接:https://www.haomeiwen.com/subject/xxnchctx.html