系列文章
- redux 实现
- react-redux 实现
- redux中间件的应用与实现
文章目录
- 什么是中间件
- redux中使用
- 分析源码
-
- createStore 部分源码
- applyMiddleware 源码
- compose 源码
- 写一个中间件
-
- logger
- promise
什么是中间件
中间件其实是对某些功能的一个增强,类似前置处理,
- 在Redux中是将 dispatch 增强改造的函数(中间件)先存起来,然后提供Redux.
- Redux 责依次执行 这样每一个中间件都对dispatch 依次进行改造,并将改造后的dispatch next 向下传递,即将控制权转移给下一个中间件,完成进一步的增强。
redux中使用
import {
createStore, applyMiddleware } from 'redux'
import rootReducer from './store/reducer'
import promise from 'redux-promse'
import createLogger from 'redux-logger'const middleware = [createLogger,promise]
const store=createStore(rootReducer,applyMiddleware(...middleware))
分析源码
createStore 部分源码
export default function createStore(reducer,preloadeState,enhancer){
//...if (typeof enhancer !== 'undefined') {
if (typeof enhancer !== 'function') {
throw new Error('Expected the enhancer to be a function.')}return enhancer(createStore)(reducer, preloadedState) }
//...
}
对于applyMiddlewares执行如下形式:
applyMiddleware(...middlewares) (createStore) (reducer, initialState)
applyMiddleware 源码
function applyMiddleware(...middlewares){
return next=>{
(reducer,initalState)=>{
const store=next(reducer,initalState);const dispatch=store.dispatch;const chain=[];const middlewareAPI={
getState:store.getState,dispatch:(action)=>dispatch(action)};chain=middlewares.map(middleware=>middleware(middlewareAPI));dispatch=compose(...chain,store.dispatch);return {
...store,dispatch}}}
}
compose 源码
function compose(...funcs){
if(funcs.length===0){
return arg=>arg}if(funcs.length===1){
return funcs[0]}return funcs.reduce((a,b)=>(...args)=>a(b(...args)))
}
关于 compose 简单实现
const compose=(a,b)=>(...args)=>a(b(...args));let data=parseFloat('3.56');
let number=Math.round(data);
console.log(number);let num=compose(Math.round,parseFloat);
console.log(num('3.56')===number)
写一个中间件
固定模式如下:
const middleware= store => next => action => {
//...
logger
const logger=(store)=>next=>{
if(!console.group){
return next}//返回一个增加日志的 全新dispatchreturn (action)=>{
console.group(action.type);//打印更新之前stateconsole.log('prev state',store.getState());console.log('action',action);//调用原始的 dispatch并记录返回值const returnValue=next(action);//打印更新之后stateconsole.log('next state',store.getState());return returnValue}
}
promise
const promise = store => next => action => {
//对 action 进行判断,当是一个promise时if (typeof action.then === "function") {
return action.then(next);}return next(action);
};