基本中间件: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中间件很是容易实现。