Redux原始碼完全解讀

Zwe1發表於2019-03-22

注:redux核心程式碼位於src目錄下,因此以目錄結構來分析,文中僅貼上部分核心程式碼。

src

index.js

import createStore from './createStore'
// 省略匯入
......

// 定義一個空函式
function isCrushed() {}
// 程式碼壓縮後,會對變數進行重新命名,也就是通過這種方式,減少位元組,判斷函式名是否發生變化
// 來確定是否使用了壓縮後的版本。
if (
  process.env.NODE_ENV !== 'production' &&
  typeof isCrushed.name === 'string' &&
  isCrushed.name !== 'isCrushed'
) {
  // 判斷函式的執行環境,在非生產環境下執行時,isCrushed函式名不是'isCrushed',則說明
  // 自視執行的是壓縮後程式碼,對開發者提出警告⚠️開發環境下使用壓縮檔案,會增加額外的構建時間。
  warning(
    'You are currently using minified code outside of NODE_ENV === "production"......' 
  )
}

// 輸出redux的核心api
export {
  createStore,
  combineReducers,
  bindActionCreators,
  applyMiddleware,
  compose,
  __DO_NOT_USE__ActionTypes
}
複製程式碼

createStore

import $$observable from 'symbol-observable'

import ActionTypes from './utils/actionTypes'
import isPlainObject from './utils/isPlainObject'

/**
 * @param {Function} reducer A function that returns the next state tree, given
 * the current state tree and the action to handle.
 *
 * @param {any} [preloadedState] The initial state. You may optionally specify it
 * to hydrate the state from the server in universal apps, or to restore a
 * previously serialized user session.
 * If you use `combineReducers` to produce the root reducer function, this must be
 * an object with the same shape as `combineReducers` keys.
 *
 * @param {Function} [enhancer] The store enhancer. You may optionally specify it
 * to enhance the store with third-party capabilities such as middleware,
 * time travel, persistence, etc. The only store enhancer that ships with Redux
 * is `applyMiddleware()`.
 *
 * @returns {Store} A Redux store that lets you read the state, dispatch actions
 * and subscribe to changes.
 */
// createStore構建一個全域性唯一的store用於儲存全域性狀態。store是一個樹?結構物件,可讀並在一定情況下
// 可寫,當然你也可以直接對sotre物件進行改寫,那麼產生的出乎意料的bug也會讓你驚喜,redux本身並沒有對
// store的寫操作進行限制,全憑使用者的自覺。ps:為了不出bug,不要直接改寫store資料。
export default function createStore(reducer, preloadedState, enhancer) {
  // createStore接收最多三個引數
  // @reducer<:Function> 一個純函式衍生器,用於從舊的狀態,衍生新的狀態,並且這個新狀態是全新的拷貝。
  // preloadedState<:Object> 初始化狀態,用於從一個基礎狀態構建一個初始store。
  // enhance<:Function> reducer的增強器,可以呼叫比如中介軟體函式等,來增強redux功能。
  if (typeof preloadedState === 'function' && typeof enhancer === 'undefined') {
    // enhancer可能是第二個引數,此時需要糾正各引數值。曾考慮為什麼不將enhancer和preloadedState引數
    // 調換位置,如此便不需要這一步處理,後想到大多數情況下我們可能不會使用enhancer,所以在引數設計時,儘量
    // 將次要引數的位置向後,或通過物件{key:value}的形式傳入。
    enhancer = preloadedState
    preloadedState = undefined
  }

  if (typeof enhancer !== 'undefined') {
    if (typeof enhancer !== 'function') {
      // enhancer必須為一個function
      throw new Error('Expected the enhancer to be a function.')
    }
    // 如果傳入了enhancer,則使用enhaner增強createReducer函式,最後生成store
    return enhancer(createStore)(reducer, preloadedState)
  }

  if (typeof reducer !== 'function') {
    // 型別校驗
    throw new Error('Expected the reducer to be a function.')
  }

  // 預定義一系列可用變數
  let currentReducer = reducer
  let currentState = preloadedState
  let currentListeners = []
  let nextListeners = currentListeners
  let isDispatching = false

  function ensureCanMutateNextListeners() {
    // 註冊事件儲存在棧中,當前後兩次棧相同時,進行一次拷貝,因為通常操作的nextListeners,這是
    // 最新的事件棧。防止在操作nextListeners時進行了寫操作,導致修改了currentListeners。
    if (nextListeners === currentListeners) {
      nextListeners = currentListeners.slice()
    }
  }

  /**
   * @returns {any} The current state tree of your application.
   */
  function getState() {
    // getState方法很簡單,直接返回當前的store,即返回currentState。獲取store時,可能
    // 正處於某個action在dispatch的狀態,那麼此時的state,我們必然可以從元件內獲取,不需要
    // 通過api來獲取。
    // 假設:如果在dispatch時獲取state,這種行為往往和我們預期不太相同,因為我們通常想要獲取的
    // 是最新狀態的state,而此時的store狀態即將被更新。
    if (isDispatching) {
      throw new Error(
        'You may not call store.getState() while the reducer is executing...... ' 
      )
    }

    return currentState
  }

  /**
   * @param {Function} listener A callback to be invoked on every dispatch.
   * @returns {Function} A function to remove this change listener.
   */
  function subscribe(listener) {
    // redux支援訂閱store狀態的變化,可向subscribe傳入一個註冊函式。
    if (typeof listener !== 'function') {
      // 型別校驗
      throw new Error('Expected the listener to be a function.')
    }

    if (isDispatching) {
      // 禁止在dispatch過程中進行訂閱。
      throw new Error(
        'You may not call store.subscribe() while the reducer is executing. ' +
          'If you would like to be notified after the store has been updated, subscribe from a ' +
          'component and invoke store.getState() in the callback to access the latest state. ' +
          'See https://redux.js.org/api-reference/store#subscribe(listener) for more details.'
      )
    }

    let isSubscribed = true
		// 確保可以安全操作nextListeners
    ensureCanMutateNextListeners()
    // 將訂閱函式推入訂閱棧
    nextListeners.push(listener)
    // 訂閱完成後,返回一個取消訂閱的方法
    return function unsubscribe() {
      if (!isSubscribed) {
        // 防止反覆取消訂閱,後面使用了splice方法,保證不會取訂錯誤的函式
        return
      }

      if (isDispatching) {
        // dispatch時禁止取消訂閱
        throw new Error(
          'You may not unsubscribe from a store listener while the reducer is executing. ' +
            'See https://redux.js.org/api-reference/store#subscribe(listener) for more details.'
        )
      }

      isSubscribed = false

      ensureCanMutateNextListeners()
      const index = nextListeners.indexOf(listener)
      // 將訂閱函式從訂閱棧中清除
      nextListeners.splice(index, 1)
    }
  }

  /**
   * Dispatches an action. It is the only way to trigger a state change.
   *
   * The `reducer` function, used to create the store, will be called with the
   * current state tree and the given `action`. Its return value will
   * be considered the **next** state of the tree, and the change listeners
   * will be notified.
   *
   * The base implementation only supports plain object actions. If you want to
   * dispatch a Promise, an Observable, a thunk, or something else, you need to
   * wrap your store creating function into the corresponding middleware. For
   * example, see the documentation for the `redux-thunk` package. Even the
   * middleware will eventually dispatch plain object actions using this method.
   *
   * @param {Object} action A plain object representing “what changed”. It is
   * a good idea to keep actions serializable so you can record and replay user
   * sessions, or use the time travelling `redux-devtools`. An action must have
   * a `type` property which may not be `undefined`. It is a good idea to use
   * string constants for action types.
   *
   * @returns {Object} For convenience, the same action object you dispatched.
   *
   * Note that, if you use a custom middleware, it may wrap `dispatch()` to
   * return something else (for example, a Promise you can await).
   */
  // dispatch是唯一可以改變store的渠道,action要求只能是簡單物件,幷包含一個type屬性
  function dispatch(action) {
    if (!isPlainObject(action)) {
      // action需要是一個簡單函式,可以是物件字面量 a = {} 或 Object.create(null)
      throw new Error(
        'Actions must be plain objects. ' +
          'Use custom middleware for async actions.'
      )
    }

    if (typeof action.type === 'undefined') {
      // 要求action必須包含type屬性
      throw new Error(
        'Actions may not have an undefined "type" property. ' +
          'Have you misspelled a constant?'
      )
    }

    if (isDispatching) {
      // 不可以同時進行多個dispatch,避免同時修改store樹?,導致狀態紊亂
      throw new Error('Reducers may not dispatch actions.')
    }

    try {
      isDispatching = true
      // 進入dispatching狀態,此時會禁止一些特殊操作,如上面的subscribe, unsubscribe, getState
      // 傳入reducer當前currentState和action生成新的store
      currentState = currentReducer(currentState, action)
    } finally {
      // store更新完畢後,修改dispatching狀態
      isDispatching = false
    }
    // dispatch後執行訂閱的回撥函式,到了兌現約定的時候了,需要通知訂閱函式,store發生變化了。
    // 並把listerners進行更新
    // 思考:其實可以在listerner複製這裡進行拷貝,便不需要ensureCanMutateNextListeners函式了
    const listeners = (currentListeners = nextListeners)
    for (let i = 0; i < listeners.length; i++) {
      const listener = listeners[i]
      // 問題:為什麼不把新的store傳給回撥函式???通過getstate嗎?
      // 答案:想了一下,傳遞store給監聽函式,有可能我們並不需要使用store,那麼傳遞後還需要一個額外
      //			的指標記憶體。可以在需要時,通過getState獲取最新的store。
      listener()
    }
		// 返回action
    return action
  }

  /**
   * @param {Function} nextReducer The reducer for the store to use instead.
   * @returns {void}
   */
  function replaceReducer(nextReducer) {
    // 作用如名字,替換reducer。如store一版,reducer也只需要一個。但在程式碼中,為了優化,可能
    // 會做一些程式碼分割的操作。可能會根據模組分割store,分割reducer。但最終還是需要將reducer
    // 組裝在一起的。
    if (typeof nextReducer !== 'function') {
      // 引數型別檢驗,nextReducer必須是函式
      throw new Error('Expected the nextReducer to be a function.')
    }
    // 替換reducer,觸發一個全域性action, 通知reducer發生了替換。
    // 問題:為什麼此處不做isDispatching的狀態限制?
    currentReducer = nextReducer
    dispatch({ type: ActionTypes.REPLACE })
  }

  /**
   * Interoperability point for observable/reactive libraries.
   * @returns {observable} A minimal observable of state changes.
   * For more information, see the observable proposal:
   * https://github.com/tc39/proposal-observable
   */
  function observable() {
    const outerSubscribe = subscribe
    return {
      /**
       * The minimal observable subscription method.
       * @param {Object} observer Any object that can be used as an observer.
       * The observer object should have a `next` method.
       * @returns {subscription} An object with an `unsubscribe` method that can
       * be used to unsubscribe the observable from the store, and prevent further
       * emission of values from the observable.
       */
      subscribe(observer) {
        if (typeof observer !== 'object' || observer === null) {
          throw new TypeError('Expected the observer to be an object.')
        }

        function observeState() {
          if (observer.next) {
            observer.next(getState())
          }
        }

        observeState()
        const unsubscribe = outerSubscribe(observeState)
        return { unsubscribe }
      },

      [$$observable]() {
        return this
      }
    }
  }

  // When a store is created, an "INIT" action is dispatched so that every
  // reducer returns their initial state. This effectively populates
  // the initial state tree.
  dispatch({ type: ActionTypes.INIT })

  return {
    dispatch,
    subscribe,
    getState,
    replaceReducer,
    [$$observable]: observable
  }
}

複製程式碼

compose

/**
 * Composes single-argument functions from right to left. The rightmost
 * function can take multiple arguments as it provides the signature for
 * the resulting composite function.
 *
 * @param {...Function} funcs The functions to compose.
 * @returns {Function} A function obtained by composing the argument functions
 * from right to left. For example, compose(f, g, h) is identical to doing
 * (...args) => f(g(h(...args))).
 */
export default function compose(...funcs) {
  // compose函式,可將多個函式引數組成合併成一個函式,引數從右自左執行。
  if (funcs.length === 0) {
    return arg => arg
  }
  // 思考: 需要加一步對引數型別的校驗,否則會引發錯誤。
	// if (funcs.some((func) => !func instanceof Function)) {
  //	throw new Error('所有引數需要是函式型別') 
  // }
  if (funcs.length === 1) {
    return funcs[0]
  }
	// reduce遍歷整個引數序列,時間複雜度On(n)。合併成的物件引數將取自最後一個函式的引數。
  return funcs.reduce((a, b) => (...args) => a(b(...args)))
}

複製程式碼

combineReducer

import ActionTypes from './utils/actionTypes'
import warning from './utils/warning'
import isPlainObject from './utils/isPlainObject'

function getUndefinedStateErrorMessage(key, action) {
  const actionType = action && action.type
  const actionDescription =
    (actionType && `action "${String(actionType)}"`) || 'an action'

  return (
    `Given ${actionDescription}, 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.`
  )
}

// 此方法用於檢查store和reduces的key是否完全匹配,不匹配則發出提示
function getUnexpectedStateShapeWarningMessage(
  inputState,
  reducers,
  action,
  unexpectedKeyCache
) {
  // 獲取傳入reducers的序列key。
  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) {
    // combineReducers接收的reducers引數必須是一個物件,內容為key:value序列。
    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)) {
    // 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('", "')}"`
    )
  }
	// state和reducers必須key匹配,unexpectedKeys為inputState中不與reducers匹配的key
  const unexpectedKeys = Object.keys(inputState).filter(
    key => !reducers.hasOwnProperty(key) && !unexpectedKeyCache[key]
  )
	// 將不匹配的key傳送給unexpectedKeyCache引數
  unexpectedKeys.forEach(key => {
    unexpectedKeyCache[key] = true
  })
	// 如果在發生replaceReducer,則退出這段程式
  if (action && action.type === ActionTypes.REPLACE) return

  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是否做了預設處理,在任何情況下都需要衍生一個新的state或返回currentState或者null
function assertReducerShape(reducers) {
  Object.keys(reducers).forEach(key => {
    const reducer = reducers[key]
    const initialState = reducer(undefined, { type: ActionTypes.INIT })

    // 測試reducer功能邊界條件處理是否健全
    if (typeof initialState === 'undefined') {
      // 保證傳入的reducers中總有一個處理通用type的case,即我們常寫的reducer函式switch語句中
      // 對於default情況的處理,通常返回上一個狀態的store。可以返回null但是不能返回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.`
      )
    }

    if (
      typeof reducer(undefined, {
        type: ActionTypes.PROBE_UNKNOWN_ACTION()
      }) === 'undefined'
    ) {
      // 通過一個隨機的驗錯type❌,來檢查reducer是否對預設情況進行了處理。對於任何未知的type,
      // reducer都需要有一個合格的返回值。並且警告⚠️不能夠對redux中內建的幾個type做處理。
      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.`
      )
    }
  })
}

/**
 * @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.
 *
 * @returns {Function} A reducer function that invokes every reducer inside the
 * passed object, and builds a state object with the same shape.
 */
// 合併reducers的核心方法,返回一個全新的reducer。
export default function combineReducers(reducers) {
  const reducerKeys = Object.keys(reducers)
  const finalReducers = {}
  // 遍歷reducers
  for (let i = 0; i < reducerKeys.length; i++) {
    const key = reducerKeys[i]

    if (process.env.NODE_ENV !== 'production') {
      if (typeof reducers[key] === 'undefined') {
        // 在非生產環境下,reducers的每一個key都需要有一個子reducer作為值,不能為undefined
        warning(`No reducer provided for key "${key}"`)
      }
    }

    if (typeof reducers[key] === 'function') {
      // 僅在reducers的各個屬性值為函式時進行復制
      finalReducers[key] = reducers[key]
    }
  }
  // finalReducers的獲取也可以這麼寫
  // const finalReducers = reducers.reduce((res, reducer, key) => {
  //   if (reducer instanceof Function) {
  //     res[key] = reducer;
	//   } else {
  //     if (process.env.NODE_ENV !== 'production') {
	//      warning(`No reducer provided for key "${key}"`)
	//     }
	//   }
  //   return res;
	// }, {})
  const finalReducerKeys = Object.keys(finalReducers)

  let unexpectedKeyCache
  if (process.env.NODE_ENV !== 'production') {
    unexpectedKeyCache = {}
  }

  let shapeAssertionError
  try {
    // 檢驗reducer是否合規
    assertReducerShape(finalReducers)
  } catch (e) {
    shapeAssertionError = e
  }
	// 最終返回的合併後的reducer
  return function combination(state = {}, action) {
    if (shapeAssertionError) {
      // 如果reducer不合規,丟擲錯誤。?
      throw shapeAssertionError
    }

    if (process.env.NODE_ENV !== 'production') {
      // 非生產環境下,檢查state和reduces的key是否完全匹配
      const warningMessage = getUnexpectedStateShapeWarningMessage(
        state,
        finalReducers,
        action,
        unexpectedKeyCache
      )
      if (warningMessage) {
        // 如果檢驗不合規,進行提示
        warning(warningMessage)
      }
    }
		// 前後狀態是否發生變化
    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]
      // 使用reducer來衍生新狀態
      const nextStateForKey = reducer(previousStateForKey, action)
      if (typeof nextStateForKey === 'undefined') {
        // 如果某個action中沒對所有的邊界條件進行處理,丟擲錯誤。
        const errorMessage = getUndefinedStateErrorMessage(key, action)
        throw new Error(errorMessage)
      }
      nextState[key] = nextStateForKey
      // 判斷前後狀態是否發生了變化,只要有部分狀態發生變化,則store發生了變化
      hasChanged = hasChanged || nextStateForKey !== previousStateForKey
    }
    // store發生變化,返回新的狀態,否則返回舊狀態
    return hasChanged ? nextState : state
  }
}

複製程式碼

bindActionCreators

function bindActionCreator(actionCreator, dispatch) {
  // 核心方法,為action生成器繫結dispatch,不需要每次從store.dispatch獲取,當然這種方式也可以。
  return function() {
    // 為actioncreater繫結執行時時上下文環境,確保其執行時this指向其所屬環境
    return dispatch(actionCreator.apply(this, arguments))
  }
}

/**
 * @param {Function|Object} actionCreators An object whose values are action
 * creator functions. One handy way to obtain it is to use ES6 `import * as`
 * syntax. You may also pass a single function.
 *
 * @param {Function} dispatch The `dispatch` function available on your Redux
 * store.
 *
 * @returns {Function|Object} The object mimicking the original object, but with
 * every action creator wrapped into the `dispatch` call. If you passed a
 * function as `actionCreators`, the return value will also be a single
 * function.
 */
// 輸出方法
export default function bindActionCreators(actionCreators, dispatch) {
  if (typeof actionCreators === 'function') {
    // 如果直接傳入了一個函式,則直接進行繫結
    return bindActionCreator(actionCreators, dispatch)
  }

  if (typeof actionCreators !== 'object' || actionCreators === null) {
    // actionCreators型別校驗,必須為物件型別或函式。
    throw new Error(
      `bindActionCreators expected an object or a function, instead received ${
        actionCreators === null ? 'null' : typeof actionCreators
      }. ` +
        `Did you write "import ActionCreators from" instead of "import * as ActionCreators from"?`
    )
  }

  const keys = Object.keys(actionCreators)
  const boundActionCreators = {}
  for (let i = 0; i < keys.length; i++) {
    const key = keys[i]
    const actionCreator = actionCreators[key]
    if (typeof actionCreator === 'function') {
      // 檢驗actionCreators中每個actionCreator是否為函式
      // 僅為actionCreator是函式的部分繫結dispatch
      boundActionCreators[key] = bindActionCreator(actionCreator, dispatch)
    }
  }
  // 返回繫結dispatch後的actionCreators 
  return boundActionCreators
}

複製程式碼

applyMiddleware

import compose from './compose'

/**
 * Creates a store enhancer that applies middleware to the dispatch method
 * of the Redux store. This is handy for a variety of tasks, such as expressing
 * asynchronous actions in a concise manner, or logging every action payload.
 *
 * See `redux-thunk` package as an example of the Redux middleware.
 *
 * Because middleware is potentially asynchronous, this should be the first
 * store enhancer in the composition chain.
 *
 * Note that each middleware will be given the `dispatch` and `getState` functions
 * as named arguments.
 *
 * @param {...Function} middlewares The middleware chain to be applied.
 * @returns {Function} A store enhancer applying the middleware.
 */
export default function applyMiddleware(...middlewares) {
  return createStore => (...args) => {
    const store = createStore(...args)
    let dispatch = () => {
      throw new Error(
        `Dispatching while constructing your middleware is not allowed. ` +
          `Other middleware would not be applied to this dispatch.`
      )
    }

    const middlewareAPI = {
      getState: store.getState,
      dispatch: (...args) => dispatch(...args)
    }
    // 遍歷呼叫middware增強dispatch方法,中介軟體可以鏈式合併。
    const chain = middlewares.map(middleware => middleware(middlewareAPI))
    dispatch = compose(...chain)(store.dispatch)

    return {
      ...store,
      dispatch
    }
  }
}

複製程式碼

utils

actionTypes

/**
 * These are private action types reserved by Redux.
 * For any unknown actions, you must return the current state.
 * If the current state is undefined, you must return the initial state.
 * Do not reference these action types directly in your code.
 */

const randomString = () =>
  Math.random()
    .toString(36)
    .substring(7)
    .split('')
    .join('.')
// redux內建的action type, 用於在store初始化,replaceReducer,注入程式碼時通知或校驗
const ActionTypes = {
  INIT: `@@redux/INIT${randomString()}`,
  REPLACE: `@@redux/REPLACE${randomString()}`,
  PROBE_UNKNOWN_ACTION: () => `@@redux/PROBE_UNKNOWN_ACTION${randomString()}`
}

export default ActionTypes

複製程式碼

isPlainObject

/**
 * @param {any} obj The object to inspect.
 * @returns {boolean} True if the argument appears to be a plain object.
 */
export default function isPlainObject(obj) {
  if (typeof obj !== 'object' || obj === null) return false

  let proto = obj
  while (Object.getPrototypeOf(proto) !== null) {
    // 最終proto為Object
    proto = Object.getPrototypeOf(proto)
  }
  // 判斷obj是不是物件字面量或Object構建的例項物件
  return Object.getPrototypeOf(obj) === proto
}

複製程式碼

warning

/**
 * Prints a warning in the console if it exists.
 *
 * @param {String} message The warning message.
 * @returns {void}
 */
export default function warning(message) {
  /* eslint-disable no-console */
  // 判斷console方法是否可呼叫
  if (typeof console !== 'undefined' && typeof console.error === 'function') {
    console.error(message)
  }
  /* eslint-enable no-console */
  // 丟擲警告資訊⚠️,如果開啟異常斷點,則會在自處停止
  try {
    // This error was thrown as a convenience so that if you enable
    // "break on all exceptions" in your console,
    // it would pause the execution at this line.
    throw new Error(message)
  } catch (e) {} // eslint-disable-line no-empty
}
複製程式碼

Redux閱讀體驗

學習到

  1. Object.keys(someobj).map((v, k) => someobj[k])

    可以替代for...of...
    支援es6可以使用Objec.entries

  2. compose方法的reduce實現,reduce真的很強!

(...args) => (..params) => args.reduce((res, curr) => res(curr(..params)))
// reduce便捷在於返回的無限制和累積效應
// 無論是map, foreach, for...in...都無法達到這麼優秀的品質
複製程式碼
  1. let lock = true;/* somewhere */ lock = false;

    想不到合適名字,就叫執行鎖,開發中這種模式很常用,一個bool型別的變數,便可以區別兩種狀態,就像暫存器的兩個狀態。

  2. 介面設計

export {
  createStore,
  combineReducers,
  bindActionCreators,
  applyMiddleware,
  compose,
  __DO_NOT_USE__ActionTypes
}
複製程式碼
只暴露儘可能少且必要的介面,介面名可以體現功效。  
複製程式碼
  1. 程式碼死,人要靈活,觀察到語言的規則和現象,都可以被利用。
function isCrushed() {} 
在壓縮情況下isCrushed.name !== 'isCrushed'
複製程式碼
  1. 邊界校驗,是保證程式碼質量的必要手段。

    js是動態語言,所以變數的型別執行時可被任意改變,型別校驗就更必要了。

優點

  1. redux自身體積很小,小几百行程式碼,對於一個大型專案來說,體積上簡直是冰山一角,所以不必擔心包大小。
  2. flux架構的踐行者,結合 react,mvc工作流,管理你的應用狀態。
  3. 單向流,以前總覺的單向流用起來很不爽快,狀態鏈任性組織,隨著工程越來越大,維護也越來越難,難到自己寫的程式碼都看不清晰。所以要讓你的應用易於組織,易於維護,那就讓你的資料流儘量簡單。就像,世間凡事大河,定然不會有勾纏旋繞,方能源遠流長,萬流匯聚。
  4. 原始碼讀起來很流暢,瞭解flux架構後,完全可以自己閱讀原始碼進行學習。

不足

  1. 細粒度控制不夠好,對於狀態的更新,監聽(subscribe)都是全量的,可以比較mobx。
  2. 不支援非同步操作,需要配合thunk,saga等中介軟體。
  3. 單向流意味著靈活度的降低,當然這是易於組織維護的代價,並且需要額外增加許多模版程式碼。
  4. reducers的合併也僅僅支援到一維,超複雜場景或許需要一個樹?結構的reducer。

相關文章