基本中間件:javascript
const customMiddleware = store => next => action => { if(action.type !== 'CUSTOM_ACT_TYPE') { return next(action) // 其餘代碼 } }
使用:html
import {createStore, applyMiddleware} from 'redux'; import reducer from './reducer'; import customMiddleware from './customMiddleware'; const store = createStore(reducer, applyMiddleware(customMiddleware));
store => next => action =>
看起來很複雜有木有。基本上你是在寫一個一層一層往外返回的方法,調用的時候是這樣的:java
let dispatched = null; let next = actionAttempt => dispatched = actionAttempt; const dispatch = customMiddleware(store)(next); dispatch({ type: 'custom', value: 'test' });
你作的只是串行化的函數調用,並在每次的調用上傳入適當的參數。當我第一次看到這個的時候,我也被這麼長的函數調用串驚呆了。可是,在讀了編寫redux測試以後就理解是怎麼回事了。react
因此如今咱們理解了函數調用串是怎麼工做的了,咱們來解釋一下這個中間件的第一行代碼:ajax
if(action.type !== 'custom') { return next(action); }
應該有什麼辦法能夠區分什麼action能夠被中間件使用。在這個例子裏,咱們判斷action的type爲非custom的時候就調用next
方法,其餘的會傳導到其餘的中間件裏知道reducer。json
redux的官方指導裏有幾個不錯的例子,我在這裏詳細解釋一下。redux
咱們有一個這樣的action:api
dispatch({ type: 'ajax', url: 'http://some-api.com', method: 'POST', body: state => ({ title: state.title, description: state.description }), cb: response => console.log('finished', response) })
咱們要實現一個POST請求,而後調用cb
這個回調方法。看起來是這樣的:app
import fetch from 'isomorphic-fetch' const ajaxMiddleware = store => next => action => { if(action.type !== 'ajax') return next(action); fetch(action.url, { method: action.method, body: JSON.stringify(action.body(store.getState())) }).then(response => response.json()) .then(json => action.cb(json)) }
很是的簡單。你能夠在中間件裏調用redux提供的每個方法。若是咱們要回調方法dispatch更多的action該如何處理呢?函數
.then(json => action.cb(json, store.dispatch))
只要修改上例的最後一行就能夠搞定。
而後在回調方法定義裏,咱們能夠這樣:
cb: (response, dispatch) => dispatch(newAction(response))
As you can see, middleware is very easy to write in redux. You can pass store state back to actions, and so much more. If you need any help or if I didn’t go into detail enough, feel free to leave a comment below!
如你所見,redux中間件很是容易實現。