【问题标题】:Why do redux-thunks need to be bound to dispatch?为什么 redux-thunks 需要绑定 dispatch?
【发布时间】:2017-05-08 21:53:44
【问题描述】:

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

然而,当我们有一个 redux-thunk 返回一个函数,该函数将在我们的动作创建者上调用 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 流程,我不明白为什么考虑到它返回的函数会使用 dispatch 调用我们的动作创建者。任何人都可以澄清我在这里似乎缺少什么吗?

【问题讨论】:

  • 将此视为另一个减速器。

标签: javascript reactjs redux redux-thunk


【解决方案1】:

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

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

为什么 redux-thunk 也必须用 dispatch 调用?

就像您在第一段中正确指出的那样,对于要由 redux 中间件链评估的动作/thunk,调用代码必须是 dispatched。

我认为误解就在这里:

"...当我们有一个 redux-thunk 它返回一个函数时 在我们的动作创建者上调用 dispatch..."。

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

现在,让我们考虑一下当前的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 作为第一个参数,以便稍后允许调度其他操作。到目前为止,尚未在您的 addPersonSuccess 操作上调用 dispatch。只有在您异步调用添加人员之后,才会在 addPersonSuccess 上调用调度。

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

参考

【讨论】:

    猜你喜欢
    • 2021-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多