目的: 通过compose组合函数方式 重写store.dispath方法
核心原理:看注释
// createStore(reducer, preloadedState, enhancer)通过判断第二个或者第三个参数是否为方法来判断
// 是否运用中间件
// enhancer = applyMiddleware(func1,loggerMiddleware) 中间件的运用函数
// 有中间件的情况return enhancer(createStore)(reducer, preloadedState)
// 先生成旧的store再和dispath合并合成新的store
const applyMiddleware = (...middlewares) => (createStore) => (reducer, preloadedState) =>{
const store = createStore(...args)
//给middleware 统一分配store
const chain = middlewares.map(middleware => middleware(store))
dispatch = compose(...chain)(store.dispatch)
//返回一个通过解构 重写dispath 新的store
return {
...store,
dispatch
}
}
// 此处 next 为 store.dispatch
const loggerMiddleware = store => next => action => {
console.log('this state', store.getState());
console.log('action', action);
next(action);
console.log('next state', store.getState());
};
redux-thunk
thunk就是简单的action作为函数,在action进行异步操作,发出新的action。
https://www.jianshu.com/p/ae7b5a2f78ae
业务场景例子 下单流程 中间件注册 校验逻辑
const compose = (funcs) => (val) => funcs.reduce(async (pre, cru) => (await cru(pre)), val)
const poinMainCheck = async (next) => {
console.log('check start')
await new Promise((res) => {
setTimeout(() => {
res()
}, 5 * 1000)
})
next()
console.log('check over')
}
const toOrder = () => {
console.log('toOrder')
return 111
}
const applyMiddleware = (funcs) => compose(funcs)(toOrder)
applyMiddleware([poinMainCheck])