redux-thunk 源码学习记录

redux触发store更新,使用的dispatch(action),在关于createStore的源码解读中能够看到,store.dispatch限制了action必须是一个纯对象。是为了保持reducer的纯净性redux

只要传入参数相同,返回计算获得的下一个 state 就必定相同。没有特殊状况、没有反作用,没有 API 请求、没有变量修改,单纯执行计算。app

redux-thunk是redux推荐的一个异步处理middleware,它能够在触发store.dispatch以前完成reducer中不能搞定的反作用,好比异步操做。异步

源码实现

function createThunkMiddleware(extraArgument) {
  return ({ dispatch, getState }) => next => action => {
    // 若是ation是函数,这调用这个函数,而且传入dispatch和getState
    if (typeof action === 'function') {
      // 此处的dispatch是在applyMiddleware中改写过的
      return action(dispatch, getState, extraArgument);
    }

    // 若是是对象,这调用下一个middleware
    return next(action);
  };
}

const thunk = createThunkMiddleware(); // 返回一个middleware
// 提供原函数,能够传递额外的参数
thunk.withExtraArgument = createThunkMiddleware;

export default thunk;

redux-thunk这个middleware能够接受函数类型的action,在action函数中进行各类自定义的操做(延时,接口请求等),而后再使用传入的dispatch触发实际的action动做(纯对象)。这样就不会影响reducer的纯洁性。函数

实例

异步的actionspa

export function logTime (time) {
    return {
        type: LOG_TIME,
        time
    }
}

export function delayLogTime () {
    let now = new Date().toString();
    return (dispatch) => { //可接受dispatch,getState
        // 进行反作用操做
        setTimeout( ()=> {
            // 实际触发ation
            dispatch(logTime(`${now} --- ${new Date().toString()}`))
        },1000)
    }
}

使用redux-thunkcode

import thunk from 'redux-thunk'

let store = createStore(reducer,applyMiddleware(thunk))
相关文章
相关标签/搜索