【问题标题】:Why my dispatch function in Redux gets a function instead of an action?为什么我在 Redux 中的 dispatch 函数得到一个函数而不是一个动作?
【发布时间】:2021-03-02 19:31:10
【问题描述】:

我有这样的代码:

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 而不是一个函数,所以我很困惑。当然,代码运行良好,我只是对这种特殊机制感兴趣,对这里发生的事情感兴趣。

【问题讨论】:

    标签: redux dispatch


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-30
      • 2017-06-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多