理解redux中間件

redux questions :
1. reducers 函數如何建立和聚合
2. action建立函數如何如何包裹在dispatch函數中
3. 如何給默認的dispatch方法增長中間件能力

middleware:
(js context)中間件由函數組合的形式建立,實現與主要執行任務正交的功能。
tips:相似的有裝飾器模式

在 redux middleware 要裝飾的主要功能是 dispatch 函數。dispatch 函數的主要功能是發送actions 給
reducer函數來產生新的state。

applyMiddleware.js

1. 函數組合
    f(x) = 2x 
    g(x) = x^2+3x+1
    (f * g)(x) = f(g(x)) = f(2x) = 4x^2 + 6x + 1
    組合兩個或者更多的函數,返回一個新的函數

    function compose(f,g){
        return x=>f(g(x))
    }
    從裏向外求值

2. 柯里化(curring)
    經過柯里化,能夠建立一個擁有部分信息的新函數
    (bind some information)

    function curring(a){
        return b=>a+b
    }

    經過函數組合和柯里化可以爲數據處理建立一個管道

redux midddleware 被設計用來在daispatch調用以前建立組合在一塊兒的函數。

對dispatch的過程作包裝,不改變任何值。
 1 export default function applyMiddleware(...middlewares) {
 2         return createStore => (...args) => {
 3             const store = createStore(...args)
 4             let dispatch = () => {
 5                 throw new Error(
 6                     'Dispatching while constructing your middleware is not allowed. ' +
 7                     'Other middleware would not be applied to this dispatch.'
 8                 )
 9             }
10 
11             const middlewareAPI = {
12                 getState: store.getState,
13                 dispatch: (...args) => dispatch(...args)
14             }
15             const chain = middlewares.map(middleware => middleware(middlewareAPI))
16             dispatch = compose(...chain)(store.dispatch)
17             // dispatch is the new 
18             return {
19             ...store,
20             dispatch
21             }
22         }
23     }
24 
25     //dispatch in createStore 
26     // dispatch action and run the listener callBack
27     function dispatch(action) {
28         try {
29             isDispatching = true
30             currentState = currentReducer(currentState, action)
31         } finally {
32             isDispatching = false
33         }
34 
35         const listeners = (currentListeners = nextListeners)
36         for (let i = 0; i < listeners.length; i++) {
37             const listener = listeners[i]
38             listener()
39         }
40 
41         return action
42     }
43 
44 
45     // In createStore.js, the enhance is the function returned by applyMiddleware 
46     // return a store which dispatch is decorated
47     enhance(createStore)(reducer,preloadState)
48 
49     //  example looger middleware
50     function logger({getState})=>{
51         return (next)=>(action)=>{
52             // action 
53             const returnNext = next(action)
54             const state = getState()
55             console.log(`${ation.type}=>${state}`)
56             // doSomething
57             return returnNext
58         }
59     }

 參考:redux

      https://medium.com/@meagle/understanding-87566abcfb7a數組

相關文章
相關標籤/搜索