简易实现: redux中间件(redux-thunk为例)
Opened this issue · 1 comments
lewenweijia commented
const myThunk = ({ dispatch, getState }) => next => action => {
if (typeof action === 'function') {
return action(dispatch, getState);
} else {
next(action);
}
}
lewenweijia commented
redux中是如何消费中间件的(将middlware串联起来)
// 中间件注入
const store = createStore(reducer, applyMiddleware(middlewares));
中间件串联实现
const middlewareAPI = {
getState: store.getState,
dispatch: (action ...args) => store.dispatch(action, ...args);
}
const chain = middlewares.map(m => m(middlewareAPI));
compose(...chain)(store.dispatch)
compose实现
const compose = fns => fns.reduce((a, b) => (...args) => a(b(..args)))