美文网首页
redux-thunk最简单的讲解,7行代码用就完事了

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

作者: 罗坤_23333 | 来源:发表于2020-06-30 16:11 被阅读0次

with no redux-thunk

  • 执行同步action

    // 同步action
    function decrement(){
       return -1
    }
    const mapDispatchToProps = (dispatch) => {
       return {
          increment: () => dispatch({ type: 'INCREMENT', payload: 1}),
          decrement: () => dispatch( decrement() )
       }
    }
    
  • 执行异步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}的函数

缺点:

  1. 在decrement函数中无法获得其他reducers的state值,即getState()
  2. 无法直接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)
        }else {
            return action;
        }
    }

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/redux-thunk
同步发布于简书知乎微信公众号
关注微信公众号:Github星探 了解更多宝藏库

相关文章

网友评论

      本文标题:redux-thunk最简单的讲解,7行代码用就完事了

      本文链接:https://www.haomeiwen.com/subject/qfsxqktx.html