小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。
简介
这个系列的文章是 redux 学习笔记,会从用法和源码分析的角度介绍 redux 的 api,不是最新的版本,但是代码的分析应该会让读者有一些收获~
系列文章
combineReducer(reducer)
两个作用:
- 找到对应的 state 分支
- 将改变后的 state 合并回树里
传入的 reducer 是键值对的形式,首先用 Object.keys 取出所有的 key,筛选出所有符合条件的 reducer (值为一个函数),然后遍历符合条件的 key,取出对应的 key 和 reducer。
执行这个 reducer,会返回当前分支下新的 state,判断当前分支下新的 state 是不是和原来的 state 引用相同,因为 reducer 中对于 state 的改变,会重新生成一个对象,不会与原来的对象引用相同。
每次 dispatch 新的 action,都会遍历所有的 reducer,找到相应的方法,替换掉 store tree 上对应的 state,更新整个 store tree。
var nextState = {}
for (var i = 0; i < finalReducerKeys.length; i++) {
var key = finalReducerKeys[i]
var reducer = finalReducers[key]
var previousStateForKey = state[key]
var nextStateForKey = reducer(previousStateForKey, action)
if (typeof nextStateForKey === 'undefined') {
var errorMessage = getUndefinedStateErrorMessage(key, action)
throw new Error(errorMessage)
}
nextState[key] = nextStateForKey
hasChanged = hasChanged || nextStateForKey !== previousStateForKey
}
return hasChanged ? nextState : state
所以 combineReducer 还是遍历了所有的 reducer,更新了整个 store tree,因为在 createStore 的 dispatch 里需要返回整个的 state。
combineReducer 的作用是不用将每个页面对不同 action 的处理都写到一个文件再传到 createStore 里,可以不用页面写在不同的文件中,由它来判断改变更新。
dispatch(action) 中执行的是 combineReducer(rootState, action),然后进入 combineReducer 遍历所有的 reducer,分别执行,最终更新整个 store tree。
以上是 combineReducer 相关的内容,欢迎点赞和评论~