redux createStore 源碼學(xué)習(xí)

createStore在redux類庫(kù)中是篇幅最長(zhǎng)的一個(gè)函數(shù)。它主要的作用是構(gòu)建redux的store。

當(dāng)createStore函數(shù)遇到enhance參數(shù)

function createStore(reducer, preloadedState, enhancer)

if (typeof enhancer !== 'undefined') {
    if (typeof enhancer !== 'function') {
      throw new Error('Expected the enhancer to be a function.')
    }

    return enhancer(createStore)(reducer, preloadedState)
  }


在createStore函數(shù)中,只要enhancer存在,創(chuàng)建store的過(guò)程將會(huì)在enhancer函數(shù)中完成。這保證了可以在enhancer函數(shù)中裝飾和包裝dispatch核心方法。有興趣可看:applyMiddleware源碼分析

dispatch函數(shù):


 function dispatch(action) {
    if (!isPlainObject(action)) {
      throw new Error(
        'Actions must be plain objects. ' +
        'Use custom middleware for async actions.'
      )
    }

    if (typeof action.type === 'undefined') {
      throw new Error(
        'Actions may not have an undefined "type" property. ' +
        'Have you misspelled a constant?'
      )
    }

    if (isDispatching) {
      throw new Error('Reducers may not dispatch actions.')
    }
    //這就是為什么reducer函數(shù)處理返回?cái)?shù)據(jù)出現(xiàn)錯(cuò)誤也不報(bào)錯(cuò)的原因。
    //直接在dispatch函數(shù)內(nèi)進(jìn)行錯(cuò)誤處理,reducer處理action的錯(cuò)誤并不會(huì)報(bào)給開(kāi)發(fā)者。
    //(真坑爹,這導(dǎo)致開(kāi)發(fā)者很難進(jìn)行錯(cuò)誤追蹤。)
    try {
      isDispatching = true
      currentState = currentReducer(currentState, action)
    } finally {
      isDispatching = false
    }

    const listeners = currentListeners = nextListeners
    for (let i = 0; i < listeners.length; i++) {
      const listener = listeners[i]
      listener()
    }

    return action
  }

初始化store的state


  // 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 })

源代碼中的英文注釋,已經(jīng)說(shuō)明了這一行代碼的作用。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 前言 本文 有配套視頻,可以酌情觀看。 文中內(nèi)容因各人理解不同,可能會(huì)有所偏差,歡迎朋友們聯(lián)系我討論。 文中所有內(nèi)...
    珍此良辰閱讀 12,206評(píng)論 23 111
  • 一、什么情況需要redux? 1、用戶的使用方式復(fù)雜 2、不同身份的用戶有不同的使用方式(比如普通用戶和管...
    初晨的筆記閱讀 2,136評(píng)論 0 11
  • http://gaearon.github.io/redux/index.html ,文檔在 http://rac...
    jacobbubu閱讀 80,431評(píng)論 35 198
  • 上周六參加了一個(gè)公司的面試,因?yàn)槭呛荛L(zhǎng)時(shí)間以來(lái)的第一次面試,發(fā)揮的并不是很好,有兩個(gè)下來(lái)一想就明白的問(wèn)題在當(dāng)時(shí)卻卡...
    夏爾先生閱讀 6,487評(píng)論 0 15
  • 在學(xué)習(xí)了redux過(guò)程中,了解到中間件這個(gè)名詞,但是我看了十遍,也完全就是懵逼的狀態(tài)。于是又重復(fù)敲了幾次代碼也不能...
    綽號(hào)陸拾柒閱讀 600評(píng)論 0 0

友情鏈接更多精彩內(nèi)容