【问题标题】:Trying to understand the Redux action creators试图了解 Redux 动作创建者
【发布时间】:2018-10-09 06:00:28
【问题描述】:
export const loginUser = userData => dispatch => {
  dispatch(showLoading(true));
}

这很好用

虽然这会引发错误

export const loginUser = userData => {
    dispatch(showLoading(true));  // dispatch undefined
}

如果我理解正确,第一个代码片段相当于

function loginUser(userData) {
   // dispatch is available here since its taken as a param for this inner function
    return function(dispatch){ 
        dispatch(showLoading(true));
    }
}

这意味着 dispatch 在 loginUser 函数中可用。 那为什么第二个代码sn-p中不可用。

【问题讨论】:

  • 因为第二个代码只有一个函数,而不是函数返回函数(第一个和最后一个 sn-p 中提到的 2 个函数)。 dispatch 将作为 arg 传递给第二个函数,第二个 sn-p 没有第二个函数。
  • 等效代码应该返回内部函数
  • 您没有在第二个示例中定义调度
  • Action 创建者必须返回一个带有 dispatch arg 的函数。在第二个 sn-p 中它丢失了。这就是你变得不确定的原因。

标签: javascript reactjs ecmascript-6 redux


【解决方案1】:

箭头函数等价于

export const loginUser = userData => dispatch => {
  dispatch(showLoading(true));
}

export function loginUser(userData) {
   return function(dispatch) {
      dispatch(showLoading(true));
   }
}

当您执行 loginUser 函数时,它的执行方式类似于

loginUser(userData)(dispatch);

因此dispatch 是被调用的内部函数的参数,不能作为外部函数内部的值使用。

在你的例子中

export const loginUser = userData => {
    dispatch(showLoading(true));  // dispatch undefined
}

dispatch 未定义

【讨论】:

  • 谢谢,来电 loginUser(userData)(dispatch);收拾东西
  • 另外我们不得不说,当您使用redux-thunk 中间件时,它允许您从您的操作中返回函数,否则它必须返回普通对象。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-04-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多