【问题标题】:React Redux dispatch syntaxReact Redux 调度语法
【发布时间】:2019-02-15 07:27:53
【问题描述】:

假设我有一个动作:

export const getInfoFor = user => {
    return dispatch => {
        dispatch( fetchApi(user) );
    }
}

const fetchApi = user => dispatch => {
    return( dispatch({type: SET_USER}) )  <--- ??
}

我的问题是,dispatch 是如何传递给fetchApi 中的return 的?也许让我失望的是fetchApi 中的双箭头函数。

代码有效,但我想了解它为什么有效。

【问题讨论】:

  • redux-thunk 在调用函数时传入dispatch。该文件的第 4 行:github.com/reduxjs/redux-thunk/blob/master/src/index.js
  • 你在使用 Redux-Thunk 吗?
  • 是的,我正在使用 redux-thunk。
  • dispatch 是您的参数的名称。将其更改为 myArg,您将看到
  • 是的,它可以是任何名称……但我的问题是,该物体最初是如何进入那里的。我猜@NicholasTower 回答了。仍在尝试理解 redux-thunk 代码库。

标签: javascript reactjs ecmascript-6 redux redux-thunk


【解决方案1】:

Redux thunk 是一个小型中间件,用于检查被分派到存储的 actiontypeof。如果typeof action 是function,则中间件调用该函数,将 dispatch 作为参数传递。

可以看源码here

【讨论】:

    【解决方案2】:

    你的顶层函数被 Redux-Thunk 中间件拦截,并传递dispatch, getState, customValues

    自定义值示例(来自 redux-thunk github)

    const store = createStore(
      reducer,
      applyMiddleware(thunk.withExtraArgument(api))
    )
    
    // later
    function fetchUser(id) {
      return (dispatch, getState, api) => {
        // you can use api here
      }
    }
    

    所以,简而言之,当你返回一个函数时,它来自 Redux-Thunk 中间件。

    https://github.com/reduxjs/redux-thunk

    https://github.com/reduxjs/redux-thunk/blob/master/src/index.js(@Nicholas Tower 提供)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-24
      • 2021-10-14
      • 2018-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-28
      • 2019-04-06
      相关资源
      最近更新 更多