redux的中间件

50 阅读1分钟

中间件的实现原理

redux-thunk

  • thunk

    • 实现一个redux-thunk,它可以派发函数 如:dispatch(fn())
      • 通过判断dispatch中参数是否为函数,是函数则执行并传入原dispatch和state
    function thunk(store) {
    	const next = store.dispatch // 保存原 dispatch
    	function dispatchWithFunction(action) {
    		if(typeof action === 'function'){
    			// 处理 dispatch 的函数
    			action(store.dispatch, store.getState)
    		}else{
    			next(action)
    		}
    	}
    	store.dispatch = dispatchWithFunction
    }
    
  • logDispatch

    • 在每次dispatch前后打印日志
    function log(store){
    	const next = store.dispatch
    	function logAndDispatch(action) {
            console.log('派发的action: ', action)
            next(action)
            console.log('派发后的结果: ', store.getState())
    	}
    	store.dispatch = logAndDispatch
    }
    
  • applyMiddleware

    • 应用中间件函数
    function applyMiddleware(store, ...fns){
    	fns.forEach(fn => {
    		fn(store)
    	})
    }