redux-thunk的实现原理

1,856 阅读1分钟

原理如下:
function createThunkMiddleware(extraArgument) {
  return ({ dispatch, getState }) => (next) => (action) => {
    if (typeof action === 'function') {
      return action(dispatch, getState, extraArgument);
    }

    return next(action);
  };
}

const thunk = createThunkMiddleware();
thunk.withExtraArgument = createThunkMiddleware;

export default thunk;

  它的核心代码其实只有两行,就是判断每个经过它的action:如果是function类型,就调用这个function(并传入 dispatch 和 getState 及 extraArgument 为参数),而不是任由让它到达 reducer,因为 reducer 是个纯函数,Redux 规定到达 reducer 的 action 必须是一个 plain object 类型。

使用redux-thunk:

export function loadSimStockList() {  return (dispath) => {    ApiCaller.call(Api.sim.getStockList, {      uid: Cookie.get('uid', cookieOptions)    }, (res) => {      dispath({        type: LOAD_SIM_STOCK_LIST,        list: res.data      })    })  }}

import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers/index';

const store = createStore(rootReducer, applyMiddleware(thunk));