redux的combineReducers源码,中文翻译

如果看不清楚,可以查看https://segmentfault.com/a/1190000018394259

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

  }

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 214,658评论 6 496
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,482评论 3 389
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 160,213评论 0 350
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,395评论 1 288
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,487评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,523评论 1 293
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,525评论 3 414
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,300评论 0 270
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,753评论 1 307
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,048评论 2 330
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,223评论 1 343
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,905评论 5 338
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,541评论 3 322
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,168评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,417评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,094评论 2 365
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,088评论 2 352

推荐阅读更多精彩内容

  • export const ActionTypes = {INIT:'@@redux/INIT'} // 生成一个s...
    jiandan5850阅读 481评论 0 0
  • Lua 5.1 参考手册 by Roberto Ierusalimschy, Luiz Henrique de F...
    苏黎九歌阅读 13,781评论 0 38
  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,319评论 0 10
  • 学习必备要点: 首先弄明白,Redux在使用React开发应用时,起到什么作用——状态集中管理 弄清楚Redux是...
    贺贺v5阅读 8,885评论 10 58
  • 如果可以两个人,谁会想一个人走,现实总是背道而驰。 一个人脆弱的时候,我们会特别需要一个怀抱,有时候明知道那个怀抱...
    粉黛伊人妆阅读 295评论 0 1