为什么要使用redux-thunk?

10 浏览
0 Comments

为什么要使用redux-thunk?

这个问题已经有了答案:

为什么在Redux中需要使用中间件来处理异步流?

我不理解为什么需要像redux-thunk这样的东西。据我所知,一个thunk是一个返回函数的函数。被包装的表达式和中间件的使用似乎更多地是为了混淆发生了什么。从redux-thunk的示例代码中可以看出:

import thunk from 'redux-thunk';
// Note: this API requires redux@>=3.1.0
const store = createStore(
  rootReducer,
  applyMiddleware(thunk)
);
// Meet thunks.
// A thunk is a function t hat returns a function.
// This is a thunk.
function makeASandwichWithSecretSauce(forPerson) {
  // Invert control!
  // Return a function that accepts `dispatch` so we can dispatch later.
  // Thunk middleware knows how to turn thunk async actions into actions.
  return function (dispatch) {
    return fetchSecretSauce().then(
      sauce => dispatch(makeASandwich(forPerson, sauce)),
      error => dispatch(apologize('The Sandwich Shop', forPerson, error))
    );
  };
}
// Thunk middleware lets me dispatch thunk async actions
// as if they were actions!
store.dispatch(
  makeASandwichWithSecretSauce('Me')
);

上面的代码可以更简洁、更直观地编写:

fetchSecretSauce().then(
  sauce => store.dispatch(makeASandwich('Me', sauce)),
  error => store.dispatch(apologize('The Sandwich Shop', forPerson, error))
)

我的问题是,redux-thunk满足了什么需求,它如何改进类似于上面示例的现有解决方案。

admin 更改状态以发布 2023年5月25日
0
0 Comments

Redux Thunk教授Redux识别特殊类型的行为,这些行为实际上是函数。

当一个动作创建者返回一个函数时,Redux Thunk中间件将执行该函数。这个函数不需要是纯的; 因此允许它拥有副作用,包括执行异步API调用。该函数还可以分派操作。

thunk可以用于延迟操作的调度,或仅当满足某些条件时进行调度。

如果启用了Redux Thunk中间件,每次你尝试调度一个函数而不是一个操作对象时,中间件都会调用该函数,并使用调度方法本身作为第一个参数。

由于我们“教”Redux认识这些“特殊”的操作创建者(我们称为thunk操作创建者),所以我们现在可以在任何我们使用常规操作创建者的地方使用它们。

检查一下Dan Abramov本人的这个很棒的答案,它涵盖了所有方面:https://stackoverflow.com/a/35415559/5714933

还可以查看这些链接获取更多信息:

https://github.com/gaearon/redux-thunk#motivation
http://redux.js.org/docs/advanced/AsyncActions.html

0