javascript - 为什么要使用 redux-thunk?

标签 javascript reactjs typescript react-redux redux-thunk

<分区>

我不明白需要像 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 满足什么需求,它如何改进与上述示例类似的现有解决方案。

最佳答案

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

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

thunk 可用于延迟 Action 的派发,或仅在满足特定条件时才派发。

如果启用了 Redux Thunk 中间件,任何时候您尝试分派(dispatch)函数而不是操作对象时,中间件都会调用该函数,并将分派(dispatch)方法本身作为第一个参数。

然后,由于我们“教导”Redux 识别此类“特殊” Action 创建器(我们称它们为 thunk Action 创建器),我们现在可以在我们使用常规 Action 创建器的任何地方使用它们。

查看 Dan Abramov 本人的这个很棒的答案,它涵盖了所有内容:https://stackoverflow.com/a/35415559/5714933

另请查看以下链接以获取更多信息:

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

关于javascript - 为什么要使用 redux-thunk?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43788447/

相关文章:

javascript - 无法映射 Firebase 数据库项目

typescript - knexjs、typescript 和 mariadb 的交易问题

javascript - 垂直排序 div A-Z 中的子元素

javascript - 如何在 gatsby 中添加外部 Javascript?

javascript - 为什么有时显示图像有时不显示图像?

javascript - 在 React 中处理静态文件(css、js、img)

javascript - 如何在动态字符串的react js中事件监听器或单击监听器?

angular - 如何在 Intellij 中执行自动 Tslint

javascript - 毫秒到小时格式的转换

javascript - 将 google maps api 代码移动到单独的文件 + jquery