Redux 进阶 -- 优雅的处理 async action

本文目标:希望通过买进口水果生鲜的例子,和大家探讨一下如何优雅的处理异步的 async action

例子:改善水果店购买流程

在上一篇文章 Redux 入门 -- 处理 async action 中,阿大通过请了一个采购员完成了耗时的进口商品的售卖。

但是,阿大同时也发现了一个问题:顾客要买水果生鲜的话需要找销售员,要买进口水果生鲜的话要找采购员,这样的话,顾客需要找不同的人,很麻烦。阿大想了想,能不能让顾客只找销售员,然后销售员如果有需求再找采购员采购呢。

阿大想到了办法,让销售员把所有的需求都告诉采购员,然后采购员再传递给收银员,这样,如果是需要采购的水果生鲜,就可以独自去处理了,这样就需要把采购员改成这样了:

const API = store => {
  
  // 和 收银员 对接的方式
  const next = store.dispatch;
  
  // 接管销售员传来的顾客需求
  store.dispatch = action => {

    // 处理完了之后再对接 收银员
    switch (action.type) {
      case 'BUY_IMPORTED_APPLE': fetching(2000, () => next(action)); break;
      case 'BUY_IMPORTED_EGG': fetching(3000, () => next(action)); break;
      default: next(action);
    }
  }
}

API(store);
复制代码

然后顾客来了之后就都只用找销售员了:

store.dispatch(buyApple(3));
store.dispatch(buyImportedApple(10));
store.dispatch(buyEgg(1));
store.dispatch(buyImportedEgg(10));
store.dispatch(buyApple(4));
store.dispatch(buyImportedApple(10));
store.dispatch(buyEgg(8));
store.dispatch(buyImportedEgg(10));
// {"fruit":{"apple":3,"importedApple":0},"fresh":{"egg":0,"importedEgg":0}}
// {"fruit":{"apple":3,"importedApple":0},"fresh":{"egg":1,"importedEgg":0}}
// {"fruit":{"apple":7,"importedApple":0},"fresh":{"egg":1,"importedEgg":0}}
// {"fruit":{"apple":7,"importedApple":0},"fresh":{"egg":9,"importedEgg":0}}
// {"fruit":{"apple":7,"importedApple":10},"fresh":{"egg":9,"importedEgg":0}}
// {"fruit":{"apple":7,"importedApple":20},"fresh":{"egg":9,"importedEgg":0}}
// {"fruit":{"apple":7,"importedApple":20},"fresh":{"egg":9,"importedEgg":10}}
// {"fruit":{"apple":7,"importedApple":20},"fresh":{"egg":9,"importedEgg":20}}
复制代码

嗯嗯,这样看起来就一致多了。阿大心里美滋滋~

图解

代码地址:redux入门 -- 改善水果店购买流程,直接控制台运行 node ./demo4/index.js 查看效果

上一篇:Redux 入门 -- 处理 async action

下一篇:Redux 进阶 -- 编写和使用中间件

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值