打印日誌中間件redux
let reduxLogger = (store) => (dispatch) => (action) =>{
console.log(store.getState())
dispatch(action)
console.log(store.getState())
}
複製代碼
處理異步請求promise
let reduxThunk = (store) => (dispatch) => (action) =>{
if(typeof action =='function'){
return action(dispatch,store.getState)
}
dispatch(action)
}
複製代碼
處理promisebash
let reduxPromise = (store) => (dispatch) => (action) =>{
let reduxPromise = (store) => (dispatch)=> (action)=>{
if(action.then && typeof action.then === 'function'){
// 若是返回的是一個promise 那麼不會處理失敗邏輯
return action.then(dispatch)
}
if(action.payload && action.payload.then&& typeof action.payload.then ==='function'){
return action.payload.then(function(data){
action.payload = data;
dispatch(action);
},function(err){
action.payload = err;
dispatch(action);
return Promise.reject(err);
})
}
return dispatch(action);
}
}
複製代碼
let applyMiddlewares = (middlewares)=>(createStore)=>(reducer)=>{
let store = createStore(reducer);
let chain = middlewares.map(middleware=>middleware(store))
dispatch = compose(...chain)(store.dispatch);
return {
...store,
dispatch
}
}
// compose
let compose = (funcs)=>{
return funcs.reduce((a,b)=>(...args)=>a(b(...args)))
}
複製代碼
簡要總結
app