繁体   English   中英

Redux Promise中间件如何反应将结果操作发送到调度?

[英]How does react redux promise middleware send the resulting action to the dispatch?

我试图通过反应终极版,以了解中间件的承诺文件 ,但不明白then以下部分:

const vanillaPromise = store => next => action => {
  if (typeof action.then !== 'function') {
    return next(action)
  }

  return Promise.resolve(action).then(store.dispatch)
}

then如何知道要调度什么? 该动作未作为参数传递

return Promise.resolve(action).then(function (action) {store.dispatch(action})

所以我不明白调度如何接收动作。

希望我能为您提供解释。

让我们看看您所熟悉的:

return Promise.resolve(action)
    .then(function (action) { store.dispatch(action)} )

您会看到以下部分:

function (action) { store.dispatch(action)} 

那只是一个等待传递“ action”属性的函数。

现在,当我们查看您遇到的困扰您的问题时,是这样的:

return Promise.resolve(action)
  .then(store.dispatch) // <--- this part

“调度”只是一个函数,在这种情况下,它期望一个参数。 最有可能的是一个对象-像这样:

store.dispatch({ type: 'MY_ACTION_TYPE' })}

现在,您可以像这样将其“包装”在一个封闭容器中,并且看起来很熟悉:

.then( (action) => {
   store.dispatch(action)
})

但是,我们真的需要将其“包装”到一个匿名函数中吗? 并非如此,因此我们只需要输入:store.dispatch,它是函数“ waiting”(等待)以从promise的返回中传递参数。 这样想:

 var MultiplyByTwo = (x) => x * 2

 Promise.resolve(5).then(MultiplyByTwo) 
// see here, this function is gonna be called with the resolution with the 5

当我们检查函数“ MultipleByTwo”时,它具有您熟悉的熟悉的签名: (x)=> x * 2

如果仅删除函数名称,则其相同:

Promise.resolve(5).then((x) => x * 2)

注意:您会看到resolve(5)->将该resolve.then视为链或“移交”。 当我们“ resolve(5)”时,我们将值“ 5”向前传递给“ .then”。 现在请记住,这5个值可以是任何东西……原始类型,在这种情况下为5个,是一个对象{TYPE:“ WHATEVER”},一个函数等。它只是递归了。例如,“嘿'.then',这是我的价值。

resolve(5).then(myfunction)
        |                ^
        |__>__>__>__>__>_|

重要的是要理解“ myFunction”是上面的示例,或者在我们的multipliByTwo甚至在store.dispatch示例中。它们都期望传递参数。

multiplyByTwo(x) <-- expecting one argument

否则您的函数可能不会在函数签名中声明它,但是它将在主体内部,例如。

myFunction() {
   const args = Array.from(arguments) // we grab the arguments
}

或希望有任意数量的参数

myOtherFunction(...args)

但是,是的,这些功能都需要解决方案的一些输入才能起作用。 在某些情况下,您可能并不关心返回的值,如果有的话,您只想拥有一些流控制即可……“那么”做到这一点。

希望对您有所帮助,并希望我确实回答了您的问题。 如果没有,请告诉我。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM