2017-12-18 60 views
0
const store = createStore(
    rootReducer, 
    initialState, 
    compose(
     applyMiddleware(thunk, api, wsMiddleware, createLogger()), 
     typeof window === 'object' && typeof window.devToolsExtension !== 
'undefined' 
     ? window.devToolsExtension() 
     : DevTools.instrument(), 
    ), 
); 

所以上面的是你怎麼通常會創建一個存儲,然後你有你的中間件,它開始像這樣:終極版中間件的認識指導

export default store => next => (action) => { 

我看過了,從終極版中間件部分。 org,但任何人都能更好地向我解釋這是怎麼回事?

那麼中間件是否正在接收商店?並從商店中調用下一個函數,最後使用作爲動作給出的參數(在這種情況下)。 ?

回答

1

的終極版中間件管道可以細分這樣的...

store => {...}

商店API是提供給管道的第一個參數。這允許中間件在流水線中的任何點獲得當前狀態和/或將新動作分派到商店中。

注:它具有許多與從createStore函數返回的商店相同的特性,但它不盡相同。只有dispatchgetState功能可用。

next => {...}

next參數是對鏈中的下一個中間件參考。如果沒有更多的中間件要去,那麼商店會處理這個動作(即將它傳遞給reducer)。

如果next未被調用,則該操作不會使其進入reducer。這可以有效地抑制某些不是有效操作的東西,比如函數或承諾,因爲如果Redux嘗試處理它,則會引發錯誤。

action => {...}

action說法是,被分派到商店的東西。

{...}

在這裏你將測試action,看看是否有你想用它和你是否將它傳遞到next處理程序做一些特別的東西。

一個例子

在這個例子中,我們將創建一個簡單的thunk middleware,解釋它如何使用管道的各個部分。

export default store => next => action => { 

    // if the action is a function, treat it as a thunk 
    if (typeof action === 'function') { 

    // give the store's dispatch and getState function to the thunk 
    // we want any actions dispatched by the thunk to go through the 
    // whole pipeline, so we use the store API dispatch instead of next 
    return action(store.dispatch, store.getState) 
    } else { 

    // we're not handling it, so let the next handler have a go 
    return next(action) 
    } 
} 
+0

謝謝! @ michael!你做得更清楚了 – DarkArtistry

0

符合Redux中間件API的功能。每個中間件都接收Store的dispatch和getState函數作爲命名參數,並返回一個函數。該函數將被賦予下一個中間件的調度方法,並且預計會返回一個調用next(action)的函數,該函數可能具有不同的參數,或者在不同的時間,或者根本不調用它。鏈中的最後一箇中間件將接收真實商店的調度方法作爲下一個參數,從而結束鏈。所以,中間件簽名是({getState,dispatch})=> next =>動作。

答案在applymiddleware文檔中找到。 https://redux.js.org/docs/api/applyMiddleware.html