0

我试图理解 redux 中的 thunk:

const thunk = ({ dispatch, getState }) => next => action => {
  if (typeof action === 'function') {
    return action(dispatch);
  }
  return next(action);
};

而且我无法理解为什么将参数作为对象传递(或者它是对象解构?)。为什么他们不只是被传递为dispatch, getState

4

1 回答 1

1

Redux 中间件被赋予了 Redux 存储 API 的微型版本作为最外层函数的参数。完整的商店 API 是{dispatch, subscribe, getState, replaceReducer}. 中间件只能访问{dispatch, getState}.

至于为什么它是一个对象而不是单独的参数,这只是一个实现细节

    const middlewareAPI = {
      getState: store.getState,
      dispatch: (...args) => dispatch(...args)
    }
    const chain = middlewares.map(middleware => middleware(middlewareAPI))
    dispatch = compose(...chain)(store.dispatch)
于 2020-01-22T17:05:49.613 回答