手写一个redux、applyMiddleware、thunk

本文介绍了如何使用Redux实现store,重点讲解了compose函数、applyMiddleWares中间件函数的创建,以及thunk和consoleFun中间件的实际应用。通过实例演示了中间件执行顺序和如何配合reducer进行状态管理。
摘要由CSDN通过智能技术生成

redux实现

const compose = (...funs) => {
  return funs.reduce(
    (a, b) =>
      (...args) =>
        a(b(...args))
  );
};

//实现中间件函数,函数聚合成高阶函数
const applyMiddleWares = (...funs) => {
  if (funs.length === 0) return false;
  if (Object.prototype.toString.call(funs[0]) !== "[object Function]") {
    return false;
  }

  const enhanceFuntion = compose(...funs);
  return enhanceFuntion;
};

//实现redux中的createStore
const createStore = (reducer, middleWare) => {
  let currentState;

  const dispatch = (action) => {
    currentState = reducer(currentState, action);
  };

  const getState = () => {
    return currentState;
  };

  //执行dispatch,获取初始的state值
  dispatch({ type: "INITIAL" });

  let enhanceDispatch = dispatch;

  //判断是否有middleware
  if (middleWare instanceof Function) {
    enhanceDispatch = middleWare(dispatch);
  }
  return {
    dispatch: enhanceDispatch,
    getState: getState,
  };
};

thunk

const thunk = (dispatch) => {
  return (action) => {
    if (action instanceof Function) {
      action(dispatch)
      return
    }
    dispatch(action)
  }
}

consoleFun

const consoleFun = (dispatch) => {
  return (action) => {
    const { payload } = action;
    console.log('我截获到了', payload)
    dispatch(action)
  }
}

例:

//声明一个reducer    
    const reducer = (state = 1, { type = null, payload = 1 }) => {
      switch (type) {
        case "IN": return state += payload;
          break;
        case "DE": return state -= payload;
          break;
        default: return state
      }
    }

//创建store
const store = createStore(reducer, applyMiddleWares(thunk, consoleFun))

中间件执行顺序:从外层到内层逐渐执行,先执行thunk的内容,在执行consoleFun

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值