使用redux-thunk和直接调用dispatch()有什么区别

What is the difference between using redux-thunk and calling dispatch() directly

我正处于理解 redux 状态管理的学习阶段,并且仍在尝试协商样板代码和中间件的混乱丛林,其中大部分我都相信 'good medicine'。所以我希望你能在这个可能是最基本的问题上多多包涵。

我知道 redux-thunk 允许动作创建者异步进行并在后续时间发送常规动作。例如,我可以在 actions.js:

中定义一个 thunk 动作创建者
export function startTracking() {
  return (dispatch => {
     someAsyncFunction().then(result => dispatch({
       type: types.SET_TRACKING,
       location: result
     }))
  })
}

然后像这样从 React 组件中调用它:

onPress={() => this.props.dispatch(actions.startTracking())}

我的问题是,上面的代码比简单地从异步回调内部调度一个动作有什么优势?

import { store } from '../setupRedux'
...

export function startTracking() {
 someAsyncFunction().then(result => {
   store.dispatch({
     type: types.SET_TRACKING,
     location: result
   })
 })
}

我会在我的组件中调用它

onPress={() => actions.startTracking()}

甚至

onPress={actions.startTracking}

像我在第二个示例中那样直接通过导入访问 store 有什么问题吗?

这样做没有错。来自 redux-thunk page

If you’re not sure whether you need it, you probably don’t.

redux 的创建者解释了使用它的优点:

This looks simpler but we don’t recommend this approach. The main reason we dislike it is because it forces store to be a singleton. This makes it very hard to implement server rendering. On the server, you will want each request to have its own store, so that different users get different preloaded data.

基本上,使用 redux-thunk 会在每个 action creator 文件中保存你的商店导入,你将能够拥有多个商店。这种方法还让您有机会编写更少的代码并避免意大利面条式代码。许多 redux 开发人员不喜欢导入存储和手动调度,因为如果代码分离不当(从 reducers 文件中的 action creator 文件导入 action 名称并从 reducers 文件中导入存储),它会创建循环依赖动作创建者文件)。此外,直接分派这样的操作可能会破坏中间件工作流程,即:中间件可能不会处理该操作。

但老实说,如果您还没有看到它的优势,请不要使用它。如果有一天您在异步操作方面遇到麻烦,redux-thunk 可能就是答案。