2017-06-20 148 views
2

我正在運行一個簡單的Redux reducer和存儲,但由於某種原因,reducer被默認調用。這是正常的嗎?爲什麼Reduux在Redux中默認稱爲默認值?

const apiWrapper = (state = {}, action) => { 
    switch(action.type) { 
    case "HELLO": 
     console.log("hello"); 
     return state; 
     break; 
    default: 
     console.log("default"); 
    } 
} 

const { createStore } = Redux; 

const store = createStore(apiWrapper); 

store.dispatch({ type: "HELLO" }); 

以上輸出的代碼片段:

"default" 
"hello" 

我只希望它登錄hello,爲什麼default有太多?這是一個JSBin

+0

您可以只記錄'action' ... –

+0

獲取Chrome的'Redux'插件,您實際上可以遍歷該狀態並查看觸發的所有操作以及每個步驟的狀態。 – samanime

+0

偉大的建議,謝謝@samanime – user123

回答

5

Redux在創建存儲時爲了設置初始狀態而在內部分派虛擬操作。根據Redux documentation

當創建一個存儲時,Redux會爲您的reducer分派一個虛擬動作以使用初始狀態填充存儲。你並不是想直接處理虛擬行爲。只要記住,如果給定的狀態作爲第一個參數是未定義的,那麼你的reducer應該返回某種初始狀態,並且你已經設置好了。

因此,當你減速首次調用state將因此未定義默認值{}將被使用。此外,它將轉到default的情況,因爲您不應該明確處理該操作,因此您將獲得console.log。確保返回default案例中的狀態以正確設置初始狀態。


只是出於好奇,動作類型的第一個啞呼叫終極版確實是"@@redux/INIT"這標誌着終極版正在初始化存儲和測試它。類似的事情發生在combineReducers以測試reducer中的不良模式。具體而言,在the source

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

因此,最初的調度基本上給出了每個減速機各自的狀態的片,並填充初始狀態樹。

+0

霍莉莫莉!我想你只是給了我需要的精神「點擊」,以充分理解減少和初始狀態! – user123

+0

@ user123沒問題,很高興我能幫忙! – Li357

+1

是的,來自@Andrew Li的優秀回答。您可能還想閱讀文檔中的[Structuring Reducers - Initializing State](http://redux.js.org/docs/recipes/reducers/InitializingState.html)部分,它解釋了'preloadedState' createStore()'的參數,reducer的默認值和'combineReducers()'效用函數。 – markerikson