为什么redux-thunks需要绑定dispatch?

Why do redux-thunks need to be bound to dispatch?

我想我在这里缺少一个基本的理解。我知道为了创建一个动作并因此触发 redux 事件链,必须使用 dispatch.

调用动作创建者

然而,当我们有一个 redux-thunk 时,returns 一个函数将在我们的 action creator 上调用 dispatch,为什么 redux-thunk 也必须用 dispatch 调用?

例如采用以下 redux-thunk:

function savePerson(person: Person) {
    return async (dispatch: any) => {
        delete person.cars;
        let newPerson = await axios.post('/api/people/addPeron', person);
        dispatch(addPersonSuccess(person));
    }
}

在没有 dispatch 的情况下调用这个 savePerson 函数不会触发 redux 流程,我不明白为什么考虑 returns 调用我们的动作创建器 dispatch 的函数。谁能澄清我在这里似乎缺少的东西?

所有 redux 中间件都遵循相同的总体布局:

const middleware => store => next => action => next(action);

Why must the redux-thunk also be called with dispatch?

正如您在第一段中正确指出的那样,对于要由 redux 中间件链评估的 action/thunk,它必须由调用代码 dispatch 编辑。

我认为误会来自这里:

"...when we have a redux-thunk which returns a function which will call dispatch on our action creator...".

虽然返回的函数调度一个动作是正确的,但这只是故事的一半。从技术上讲,您要调度 两次 :首先是 savePerson,然后是 addPersonSuccess。前者是一个 thunk,后者很可能是一个简单的动作。

现在,让我们考虑一下当前的 redux-thunk source code:

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

    return next(action);
  };
}

...

export default thunk;

一旦您分派 savePerson,中间件就会将您的操作识别为一个函数。然后它注入 dispatch 作为第一个参数,以便稍后允许分派其他操作。到目前为止,dispatch 尚未在您的 addPersonSuccess 操作中调用。只有在您异步调用添加人员后,才会在 addPersonSuccess.

调用调度

我喜欢将其视为在 thunk(dispatch、getState 等)中传递 redux 上下文。

参考