为什么我在 Redux 中的调度函数得到一个函数而不是一个动作?

Why my dispatch function in Redux gets a function instead of an action?

我有这样的代码:

const mapStateToProps = (state, ownProps) => ({
  historyData: getHistoryForSavedVariants(state)[ownProps.savedVariant.variantId],
  isHistoryLoading: getHistoryLoading(state),
})

const mapDispatchToProps = (dispatch, ownProps) => ({
  loadData: () => {

-----> dispatch(loadHistoryForSavedVariant(ownProps.savedVariant))

  },  
})

export default connect(mapStateToProps, mapDispatchToProps)(HistoryButton)

在另一个文件中 loadHistoryForSavedVariant 如下:

export const loadHistoryForSavedVariant = (savedVariant) => {
  return (dispatch) => {
    dispatch({ type: REQUEST_HISTORY })
    const url = `/api/saved_variant/${savedVariant.variantId}/saved_variant_history`
    new HttpRequestHelper(url,
      (responseJson) => {
        dispatch({ type: RECEIVE_HISTORY })
        dispatch({ type: RECEIVE_DATA, updatesById: responseJson })
      },  
      (e) => {
        dispatch({ type: RECEIVE_HISTORY })
        dispatch({ type: RECEIVE_DATA, error: e.message, updatesById: {} })
      },  
    ).get({ xpos: savedVariant.xpos, ref: savedVariant.ref, alt: savedVariant.alt, familyGuid: savedVariant.familyGuids[0] })
  }
}

所以,可以看出dispatch最终得到了一个函数——(dispatch) => {...}不是一个动作 .为什么?我不明白这是怎么回事。在 Redux 官方网页上,我到处都看到 dispatch 得到的是 action 而不是函数,所以我很困惑。代码当然可以正常工作,我只是对这个特定的机制感兴趣,对这里发生的事情感兴趣。

这是一个“thunk 函数”。 Thunk 是一个 Redux 中间件,允许您将函数传递给 dispatch(),这对于编写与组件分开的异步逻辑非常有用。

有关更多详细信息,请参阅这些 Redux 教程: