首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么使用redux-thunk?

为什么使用redux-thunk?
EN

Stack Overflow用户
提问于 2017-05-05 00:36:26
回答 1查看 16.6K关注 0票数 35

我不明白为什么需要像redux-thunk这样的东西。据我所知,thunk是一个返回函数的函数。在我看来,包装的表达式和中间件的使用似乎更多地混淆了正在发生的事情。摘自redux-thunk的示例代码

代码语言:javascript
复制
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')
);

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

代码语言:javascript
复制
fetchSecretSauce().then(
  sauce => store.dispatch(makeASandwich('Me', sauce)),
  error => store.dispatch(apologize('The Sandwich Shop', forPerson, error))
)

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

EN

回答 1

Stack Overflow用户

发布于 2017-05-05 00:41:30

Redux Thunk教Redux识别实际上是函数的特殊类型的动作。

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

thunk可用于延迟操作的调度,或者仅在满足特定条件时才调度。

如果启用了Redux Thunk中间件,则每当您尝试分派函数而不是操作对象时,中间件都会使用分派方法本身作为第一个参数来调用该函数。

然后,由于我们“教”Redux识别这样的“特殊”动作创建者(我们称他们为thunk动作创建者),我们现在可以在任何我们将使用常规动作创建者的地方使用它们。

请查看丹·阿布拉莫夫本人的答案,它涵盖了所有内容:https://stackoverflow.com/a/35415559/5714933

另请查看以下链接以了解更多信息:

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

票数 22
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43788447

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档