redux
代码片段
function todos(state = [], action) {
switch (action.type) {
case ADD_TODO:
...
default:
return state
}
}
import { combineReducers } from 'redux'
import todos from './todos'
import visibilityFilter from './visibilityFilter'
const rootReducer = combineReducers({
todos,
visibilityFilter
})
import { createStore } from 'redux'
import reducer from './reducers'
...
const store = createStore(reducer)
function createStore(reducer, preloadedState, enhancer) {
let currentReducer = reducer
let currentState = preloadedState
let currentListeners = []
let nextListeners = currentListeners
let isDispatching = false
function getState() {
return currentState
}
function dispatch(action) {
...
try {
isDispatching = true
currentState = currentReducer(currentState, action)
} finally {
isDispatching = false
}
...
}
dispatch({ type: ActionTypes.INIT })
return {
dispatch,
getState,
...
}
}
funciton combineReducer (reducers) {
const reducerKeys = Object.keys(reducers)
for (let i = 0; i < reducerKeys.length; i++) {
const key = reducerKeys[i]
...
if (typeof reducers[key] === 'function') {
finalReducers[key] = reducers[key]
}
}
const finalReducerKeys = Object.keys(finalReducers)
return function combination(state = {}, action) {
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)
nextState[key] = nextStateForKey
hasChanged = hasChanged || nextStateForKey !== previousStateForKey
}
return hasChanged ? nextState : state
}
}
- combineReducers函数对每个reducer做校验,返回combination函数
- 在createStore中执行 dispatch({ type: ActionTypes.INIT })即执行combination函数。
- combination函数遍历执行每一个reducer函数,const nextStateForKey = reducer(previousStateForKey, action)
- 在每个reducer函数中,action为{ type: ActionTypes.INIT }, state为undefined
- state为undefined,因此会用默认值
- 自己定义的action中不会有与之对应的case语句,因此执行switch的default语句块中.