【问题标题】:How does the inner function get the 'dispatch' parameter?内部函数如何获取'dispatch'参数?
【发布时间】:2021-04-01 07:55:41
【问题描述】:

我是 React-Redux 的新手!

但我有一个问题。

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

GetCurrentUserInfoAction Creator 函数:

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 的调用方式:

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

getCurrentUserInfo()没有收到任何参数,是不是因为被dispatch(getCurrentUserInfo())包围了?

【问题讨论】:

    标签: javascript reactjs react-redux


    【解决方案1】:

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

    export const AuthGuard = connect(
      state => ({}),
      dispatch => ({
        authOrRedirect: () => {
          return getCurrentUserInfo()(dispatch).catch(() => {
            history.replace('/login')
          })
        }
      })
    )(AuthGuardComponent)
    

    例如:

    显然你可以这样写getCurrentUserInfo()

    const getCurrentUserInfo = function(){  // create getCurrentUserInfo dispatcher
      return async function(dispatch){
        // ...
      };
    }
    

    dispatchProp 可以这样写:

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

    常见模式

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

    • 答:getCurrentUserInfo()(dispatch):调用“调度函数”
    • B:dispatch(getCurrentUserInfo()):调度一个“动作”

    (A) 适用于您的情况,因为getCurrentUserInfo() 返回一个“调度函数”(不是官方术语),即调用dispatch( someAction ) 的函数.
    getCurrentUserInfo()(dispatch) 调用这个“调度函数”。

    (B) 是一个模式,如果getCurrentUserInfo() 是一个“动作创建者”(在你的情况下不是),即返回一个“动作”的函数",比如{ type: ..., users: ... }

    【讨论】:

    • 我明白了,谢谢,顺便说一句,dispatch(getCurrentUserInfo())getCurrentUserInfo()(dispatch) 是一样的吗?
    • 没有。我更新了答案以解释这两种模式。
    • 你好,我贴的代码来自:https://github.com/huwcarwyn/react-laravel-boilerplate/blob/master/resources/assets/js/components/AuthGuard/AuthGuard.jsx,默认是这样写的:`return dispatch(getCurrentUserInfo()).catch(() => { history.replace(' /login') })` 是印刷错误吗?
    猜你喜欢
    • 2013-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-11
    • 2014-11-23
    • 2014-10-13
    • 1970-01-01
    相关资源
    最近更新 更多