首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >内部函数是如何获取“调度”参数的?

内部函数是如何获取“调度”参数的?
EN

Stack Overflow用户
提问于 2020-12-22 23:43:33
回答 1查看 63关注 0票数 3

我是新来的React-Redux!

但我有个问题。

内部函数(async dispatch)如何接收dispatch()参数?

GetCurrentUserInfo操作创建器功能:

代码语言:javascript
复制
export const getCurrentUserInfo = () => async dispatch => {
  const response = await axios.get('/api/users/me')

  dispatch({
    type: userActions.SET_CURRENT_USER_INFO,
    users: response.data.data
  })

  return response.data.data
}

getCurrentUserInfo的调用方式:

代码语言:javascript
复制
export const AuthGuard = connect(
  state => ({
    currentUserSlug: state.session.currentUser
  }),
  dispatch => ({
    authOrRedirect: () => {
      return dispatch(getCurrentUserInfo()).catch(() => {
        history.replace('/login')
      })
    }
  })
)(AuthGuardComponent)

getCurrentUserInfo()不接收任何参数,但这是因为它被封装在dispatch(getCurrentUserInfo())中吗

EN

回答 1

Stack Overflow用户

发布于 2020-12-23 02:53:38

getCurrentUserInfo()返回一个需要一个参数dispatch的函数。您需要调用返回的函数并将dispatch参数传递给它:

代码语言:javascript
复制
export const AuthGuard = connect(
  state => ({}),
  dispatch => ({
    authOrRedirect: () => {
      return getCurrentUserInfo()(dispatch).catch(() => {
        history.replace('/login')
      })
    }
  })
)(AuthGuardComponent)

例如:

显然,您可以像这样编写getCurrentUserInfo()

代码语言:javascript
复制
const getCurrentUserInfo = function(){  // create getCurrentUserInfo dispatcher
  return async function(dispatch){
    // ...
  };
}

dispatchProp可以写成这样:

代码语言:javascript
复制
export const AuthGuard = connect(
  state => ({}),
  dispatch => ({
    authOrRedirect: () => {
      const getUserInfoDispatcher = getCurrentUserInfo();  // create dispatcher
      getUserInfoDispatcher(dispatch).catch(() => {        // call dispatcher
        history.replace('/login')
      })
    }
  })
)(AuthGuardComponent)

常见模式

显然,您对这两种模式感到困惑,这两种模式您可能在某处见过:

  • A:getCurrentUserInfo()(dispatch):call a "dispatching function"
  • B:dispatch(getCurrentUserInfo()):dispatch an "action"

(A)适用于您的情况,因为getCurrentUserInfo()返回一个"dispatching function“(非正式术语),即调用dispatch( someAction )的函数。

getCurrentUserInfo()(dispatch)调用这个“调度函数”。

(B)是一种模式,如果getCurrentUserInfo()是“操作创建者”(在您的例子中不是),也就是返回“操作”的函数,如{ type: ..., users: ... },则会使用该模式。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65411634

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档