lewenweijia / notes

🏊 dive dive diving
1 stars 0 forks source link

简易实现: redux中间件(redux-thunk为例) #9

Open lewenweijia opened 5 years ago

lewenweijia commented 5 years ago
const myThunk = ({ dispatch, getState }) => next => action => {
  if (typeof action === 'function') {
    return action(dispatch, getState);
  } else {
    next(action);
  }
}
lewenweijia commented 5 years ago

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)))