redux的combineReducers源碼,中文翻譯

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) //將reducers的key提取爲數組
  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的key值複製了一份
      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...redux

相關文章
相關標籤/搜索