中间件
机制:
- 建立一个
store.dispatch
的链条,每个middleware
是链条中的一个环节,传入的action
对象逐步处理,直到最后出来是Javascript Plain Object
;
import { createStore, combineReducers, applyMiddleware } from 'redux';
// applyMiddleware takes createStore() and returns// a function with a compatible API.
let createStoreWithMiddleware = applyMiddleware(
logger,
crashReporter
)(createStore);
// Use it like you would use createStore()let todoApp = combineReducers(reducers);
let store = createStoreWithMiddleware(todoApp);
middleware
`// Logs all actions and states after they are dispatched.
const logger = store => next => action => {
console.log('dispatching', action);
let result = next(action);
console.log('next state', store.getState());
return result;
};`
- 每一个 Middleware 可以得到:
-
store
: 通过store.getState
获得最近的状态;以及通过原本的dispatch
对象直接发布action
对象;
-
next
方法: 前一个Middleware
返回的dispatch
方法;
Thunk
//Thunk middleware
const thunk = store => next => action => {
typeof action === 'function' ?
action(store.dispatch, store.getState) :
next(action);
}
export function incrementIfOdd () {
return (dispatch, getState) => {
const {counter} = getState();
if(counter % 2 === 0) return;
dispatch(increment());
}
}
export function incrementAsync(delay = 1000) {
return dispatch => {
setTimeout(()=> {
dispatch(increment());
}, delay);
}
}