react redux promise middleware 如何将结果 action 发送到 dispatch?

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

我正在尝试通过 react redux 了解 promises 的中间件 docs 但不理解下面的 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})

所以我不明白 dispatch 是如何接收动作的。

我希望我能帮忙解释一下。

让我们看看你熟悉的:

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

"dispatch" 只是一个函数,在这种情况下,它需要一个参数。很可能是一个对象 - 像这样:

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

现在,您 "could" 将它包裹在闭包中,像这样,它看起来很熟悉:

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

但是,我们真的需要在匿名函数中 "wrap" 它吗?不是真的,所以我们可以输入:store.dispatch,它是函数 "waiting" 来传递来自 promise 的 return 的参数。可以这样想:

 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 视为一个链,或 "handoff"。当我们 "resolve(5)" 时,我们将值“5”向前传递给“.then”。现在请记住,5 的值可以是任何东西……一个原始值,在本例中为 5,一个对象 {TYPE: "WHATEVER"},一个函数等。它只是放手......就像,"Hey '.then', here is my value...."

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

重要的是要理解 "myFunction" 是上面的这个例子或者我们的 multiplyByTwo 甚至那个 store.dispatch 例子..他们都期待一个传递参数。

multiplyByTwo(x) <-- expecting one argument

或者你的函数可能没有在函数签名中声明它,但它会在函数体内声明,ala..

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

或者希望有任意数量的参数

myOtherFunction(...args)

但是是的——这些职能正在期待决议的一些输入来采取行动。在某些情况下,您可能不关心 returned 值,如果有的话,您只想进行一些流量控制...这样做,"THEN" 那个..

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