redux的combineReducers源码,中文翻译

39次阅读

共计 5664 个字符,预计需要花费 15 分钟才能阅读完成。

import {ActionTypes} from ‘./createStore’
import isPlainObject from ‘lodash/isPlainObject’
import warning from ‘./utils/warning’
/**
* ActionTypes 是这个
* export const ActionTypes = {
* INIT: ‘@@redux/INIT’
* }
*/
function getUndefinedStateErrorMessage(key, action) {// 函数名翻译为获取未定义的 state 错误信息
const actionType = action && action.type
const actionName = (actionType && `”${actionType.toString()}”`) || ‘an action’

return (
`Given action ${actionName}, reducer “${key}” returned undefined. ` +
`To ignore an action, you must explicitly return the previous state. ` +
`If you want this reducer to hold no value, you can return null instead of undefined.`
)
// 对于 action xxx ,reducer yyy 返回 undefined
// 你一定要很明确的返回之前的 state, 这样就可以忽略一个 action
// 如果你想这个 reducer 没有返回值, 你可以返回 null 而不是 undefined
}

// 获取与预期不符的 state 的结构警告信息
function getUnexpectedStateShapeWarningMessage(inputState, reducers, action, unexpectedKeyCache) {
const reducerKeys = Object.keys(reducers)
const argumentName = action && action.type === ActionTypes.INIT ?
‘preloadedState argument passed to createStore’ :
‘previous state received by the reducer’

if (reducerKeys.length === 0) {
return (
‘Store does not have a valid reducer. Make sure the argument passed ‘ +
‘to combineReducers is an object whose values are reducers.’
)
}

if (!isPlainObject(inputState)) {
return (
`The ${argumentName} has unexpected type of “` +
({}).toString.call(inputState).match(/\s([a-z|A-Z]+)/)[1] +
`”. Expected argument to be an object with the following ` +
`keys: “${reducerKeys.join(‘”, “‘)}”`
)
}

const unexpectedKeys = Object.keys(inputState).filter(key =>
!reducers.hasOwnProperty(key) &&
!unexpectedKeyCache[key]
)

unexpectedKeys.forEach(key => {
unexpectedKeyCache[key] = true
})

if (unexpectedKeys.length > 0) {
return (
`Unexpected ${unexpectedKeys.length > 1 ? ‘keys’ : ‘key’} ` +
`”${unexpectedKeys.join(‘”, “‘)}” found in ${argumentName}. ` +
`Expected to find one of the known reducer keys instead: ` +
`”${reducerKeys.join(‘”, “‘)}”. Unexpected keys will be ignored.`
)
}
}

// 声明 reducer 结构
function assertReducerShape(reducers) {
Object.keys(reducers).forEach(key => {
const reducer = reducers[key]
const initialState = reducer(undefined, { type: ActionTypes.INIT})

if (typeof initialState === ‘undefined’) {
throw new Error(
`Reducer “${key}” returned undefined during initialization. ` +
`If the state passed to the reducer is undefined, you must ` +
`explicitly return the initial state. The initial state may ` +
`not be undefined. If you don’t want to set a value for this reducer, ` +
`you can use null instead of undefined.`
)
//reducer xxx 初始化时返回 undefined, 如果传给 reducer 的 state 是 undefined, 你一定要
// 很明确地返回初始 state, 初始 state 可能是 undefined, 如果你不想给这个 reducer
// 设置 value 值, 你可以用 null 代替 undefined
}

const type = ‘@@redux/PROBE_UNKNOWN_ACTION_’ + Math.random().toString(36).substring(7).split(”).join(‘.’)
if (typeof reducer(undefined, { type}) === ‘undefined’) {
throw new Error(
`Reducer “${key}” returned undefined when probed with a random type. ` +
`Don’t try to handle ${ActionTypes.INIT} or other actions in “redux/*” ` +
`namespace. They are considered private. Instead, you must return the ` +
`current state for any unknown actions, unless it is undefined, ` +
`in which case you must return the initial state, regardless of the ` +
`action type. The initial state may not be undefined, but can be null.`
)
// 当 probed(探索) 随机的 type 时,reducer xxx 返回 undefined. 不要在 ”redux/*” 命名空间操作
// ${ActionTypes.INIT}, 也就是 ’@@redux/INIT’, 或任意的 action. 他们是私有的.
// 相反, 对于未知的 action, 你应该返回当前的 state, 除非它是 undefined. 不管 action 的 type 是什么,
// 你都应该返回初始的 state, 出示的 state 可能不是 undefined, 但可以是 null
}
})
}

/**
* Turns an object whose values are different reducer functions, into a single
* reducer function. It will call every child reducer, and gather their results
* into a single state object, whose keys correspond to the keys of the passed
* reducer functions.
*
* 将一个 value 值是不同 reducer 函数的对象变成一个单一的 reducer 函数, 它将会调用每一个子 reducer
* 将它们的结果组合成一个单一的 state 对象, 这个对象的 key 对应传进来的 reducer 的 key
*
* @param {Object} reducers An object whose values correspond to different
* reducer functions that need to be combined into one. One handy way to obtain
* it is to use ES6 `import * as reducers` syntax. The reducers may never return
* undefined for any action. Instead, they should return their initial state
* if the state passed to them was undefined, and the current state for any
* unrecognized action.
*
* reducers 是一个对应不同 reducer 函数的对象, 这些 reducer 函数需要组合成一个 reducer.
* 一个很方便获取到它的方法就是使用 ES6 的 `import * as reducers` 语法,reducer 可能不会
* 返回 undefined. 相反, 它们应该返回初始的 state. 如果传给它们的 state 是 undefined, 任何
* 不被识别的 action 都会返回当前的 state
*
* @returns {Function} A reducer function that invokes every reducer inside the
* passed object, and builds a state object with the same shape.
*
* 返回一个 reducer 函数, 会触发传进来的对象中的每一个 reducer, 建立一个有相同结构的 state 对象
*/
export default function combineReducers(reducers) {
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 shapeAssertionError
try {
assertReducerShape(finalReducers)
} catch (e) {
shapeAssertionError = e
}

return function combination(state = {}, action) {
if (shapeAssertionError) {
throw shapeAssertionError
}

if (process.env.NODE_ENV !== ‘production’) {
const warningMessage = getUnexpectedStateShapeWarningMessage(state, finalReducers, action, unexpectedKeyCache)
if (warningMessage) {
warning(warningMessage)
}
}

let hasChanged = false
const nextState = {}
for (let i = 0; i < finalReducerKeys.length; i++) {//finalReducerKeys 就是 reducers 复制了一份
const key = finalReducerKeys[i] // 第 i 个 key
const reducer = finalReducers[key] //key 所对应的 reducer
const previousStateForKey = state[key] // 把 key 作为属性赋给 state
const nextStateForKey = reducer(previousStateForKey, action) // 返回新的 state
if (typeof nextStateForKey === ‘undefined’) {
const errorMessage = getUndefinedStateErrorMessage(key, action)
throw new Error(errorMessage)
}
nextState[key] = nextStateForKey // 给 nextState 添加 key 属性, 并赋值,key 与 reducer 名字相同
hasChanged = hasChanged || nextStateForKey !== previousStateForKey
}
return hasChanged ? nextState : state
}
}

源码解析请参考 https://segmentfault.com/a/11…

正文完
 0