redux异步action_redux-thunk最简单的讲解,7行代码用就完事了

cad941edfb60c0e5af56d39f1ccdc1cd.png

with no redux-thunk

1.执行同步action

// 同步action
function decrement(){
  return { type: 'INCREMENT', payload: 1 }
}
const mapDispatchToProps = (dispatch) => {
  return {
     increment: () => dispatch({ type: 'INCREMENT', payload: 1}),
     decrement: () => dispatch( decrement() )
  }
}

2.执行异步action

// 异步action
function decrement(){
  return Promise.resolve({type: 'ASYNC_ACTION'})
}
const mapDispatchToProps = (dispatch) => {
  return {
     decrement: () => dispatch( decrement() ),  // ⚠️报错!
     decrement2: () => {
        /**   ‍♀️只能在这里执行.then,且不能很好将业务代码抽离出来**/
        decrement().then(plainObject=>{
           dispatch(plainObject)
        })
     }
  }
};
decrement报错信息: throw new Error: Actions must be plain objects,Use custom middleware for async actions. at dispatch (createStore.js:152)
dispatch内必须是一个扁平化的object,
或者是能直接返回一个 {type:'REDUCERS',payload:data}的函数
缺点:
在decrement函数中无法获得其他reducers的state值,即 getState()
无法直接dispatch一个异步返回值

with redux-thunk

const mapDispatchToProps = (dispatch) => {
  return {
     increment: () => dispatch(actionThunkify()),
  }
};

function actionThunkify(){
  return (dispatch, getState)=>{
      setTimeout(()=>{
          dispatch({ type: 'INCREMENT', payload:"" })
      },1000)
  }
}

基本实现原理

7行代码实现

redux-thunk中间件(middleware)改写了reduxdispatch()方法

function dispatch(action){
  if(typeof action === "function"){
    return action(dispatch, getState)
  }else {
      return action;
  }
}

thunkify动机

如同redux-thunk所写的[1],创建的action creators不再必须返回一个action对象,还允许返回一个function,以便可以延迟dispatch一个action或者直到满足条件时再dispatch。

btw,在Promise发明之前,常用thunk化来管理异步callback

Usage

兼容异步/同步action

    // 派送异步action
    dispatch((dispatch)=>{
        return dispatch(asyncFunction())
    });
    // 异步函数
    function asyncFunction(){
        return (dispatch)=>{
            setTimeout(()=>{
                dispatch({type:"ASYNC_ACTION"})
            },1000)
        }
    }


    // 同步函数
    dispatch((dispatch)=>{
        return dispatch({type:"SYNC_ACTION"})
    });


    // 直接对象
    dispatch({type:"PLAIN_OBJECT"})

其他

github: https:// github.com/reduxjs/redu x-thunk
同步发布于简书、知乎、微信公众号
关注微信公众号: Github星探 了解更多宝藏库
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值