React 动作如何访问 dispatch?

How does a react action have access to dispatch?

在我的 React 项目中,我有一个如下所示的操作文件:

const startLoad = () => async (dispatch) => {
  dispatch({
    type: CONTENT_LOAD,
  });
};

// Get all content
export const getContents = () => async (dispatch) => {
  dispatch(startLoad());
  // some more code...
};

所以在这个例子中,我知道调度来自 middleware 并且 getContents 可以访问它,因为它是使用 mapDispatchToProps 映射的。所以我假设当 getContents 被调用时,它真的是这样调用的 -> dispatch(getContents) 但是这可以在普通的 JavaScript 中复制所以我可以看到到底发生了什么吗?如果我对 getContents 有权访问 dispatch 的原因有误,请告诉我。

例如,startLoad 怎么能仅仅因为 dispatch 调用了 startLoad 就可以使用 dispatch?我注意到如果我这样称呼它也会起作用:dispatch(startLoad(dispatch));.

将 dispatch 传递给 startLoad 实际上对我来说更有意义,所以我不明白为什么不需要这样做。

编辑:这是我自己能想出的最接近的例子。

const fun = () => (fun2) => {
  fun2();
}

const fun2 = () => {
  console.log('hello');
}

fun()(fun2);

So I am assuming when getContents is called, its really called like this -> dispatch(getContents) but can this be replicated in plain JavaScript so I can see what is really going on? If I am wrong about why getContents has access to dispatch please let me know.

redux-thunk has quite simple implementation

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

    return next(action);
  };
}

如您所见,它会检查 action 是否是一个函数。

还有奖励,如果你愿意,你可以在 dispatch

之后获得整个状态和参数中的额外参数

For example, how isstartLoad able to use dispatch just because dispatch called startLoad? I have noticed that it will also work if I call it like this: dispatch(startLoad(dispatch));.

看来中间件也能处理上述情况。