//创建store需要传入reducer
createStore(reducer, preloadedState, enhancer)
//reducer是一个函数,传入当前state和action,返回新的state
// (preState, action) => nextState
当我们需要将多个reducer合并成一个时
combineReducers({
app: appReducer,
account: accountReducer,
})
// 传入的reducers是个对象,
combineReducers(reducers) {
//校验传入的reducers对象是否是 key-value键值对,value是function
const reducerKeys = Object.keys(reducers)
const finalReducers = {}
for (let i = 0; i < reducerKeys.length; i++) {
const key = reducerKeys[i]
if (process.env.NODE_ENV !== 'production') {
if (typeof reducers[key] === 'undefined') {
warning(`No reducer provided for key "${key}"`)
}
}
if (typeof reducers[key] === 'function') {
finalReducers[key] = reducers[key]
}
}
const finalReducerKeys = Object.keys(finalReducers)
let unexpectedKeyCache
if (process.env.NODE_ENV !== 'production') {
unexpectedKeyCache = {}
}
let sanityError
try {
assertReducerSanity(finalReducers)
} catch (e) {
sanityError = e
}
// 返回一个合并后的reducer
return function combination(state = {}, action) {
if (sanityError) {
throw sanityError
}
if (process.env.NODE_ENV !== 'production') {
const warningMessage = getUnexpectedStateShapeWarningMessage(state, finalReducers, action, unexpectedKeyCache)
if (warningMessage) {
warning(warningMessage)
}
}
//代表 state 是否改变
let hasChanged = false
const nextState = {}
// 遍历处理所有的reducer
for (let i = 0; i < finalReducerKeys.length; i++) {
const key = finalReducerKeys[i]
const reducer = finalReducers[key]
const previousStateForKey = state[key]
// 调用reducer,得到当前reducer生成的state
const nextStateForKey = reducer(previousStateForKey, action)
if (typeof nextStateForKey === 'undefined') {
const errorMessage = getUndefinedStateErrorMessage(key, action)
throw new Error(errorMessage)
}
// 判断state是否改变,判断reducer生成的对象和原先的对象是否是一个对象
nextState[key] = nextStateForKey
hasChanged = hasChanged || nextStateForKey !== previousStateForKey
}
return hasChanged ? nextState : state
}
}