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

标签 reactjs react-native redux react-redux redux-thunk

我正处于理解 redux 状态管理的学习阶段,并且仍在尝试解决样板代码和中间件的令人眼花缭乱的丛林,其中大部分我都相信是“良药”。因此,我希望您能耐心解答这个可能是基本问题。

我知道 redux-thunk 允许操作创建者异步进行并在随后的时间分派(dispatch)常规操作。例如,我可以在 actions.js 中定义一个 thunk Action 创建者:

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

并从 React 组件中调用它,如下所示:

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

我的问题是,与简单地从异步回调内部分派(dispatch)操作相比,上述代码有什么优势?

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的创建者解释了使用它的优势here :

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 会将存储导入保存在每个操作创建者文件中,并且您将能够拥有多个存储。这种方法还使您有机会编写更少的代码并避免意大利面条式代码。许多 redux 开发人员不喜欢导入 store 并手动调度,因为如果代码分离得很糟糕,它可能会创建循环依赖(从 reducer 文件中的 Action 创建者文件导入 Action 名称,并从 reducer 文件中的 reducer 文件导入存储) Action 创建者文件)。此外,直接分派(dispatch)这样的操作可能会破坏中间件工作流程,即:该操作可能不会由中间件处理。

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

关于reactjs - 使用redux-thunk和直接调用dispatch()有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47780595/

相关文章:

javascript - React-Native: Release模式下的 JavaScript 正则表达式异常(无效组)

javascript - 本例中如何正确使用useState?

javascript - 为较小的屏幕 react 渲染 html

javascript - Redux thunk - 嵌套调度函数/ Action

javascript - 如何使用切换来对状态使用react?

react-native - 在 FlatList 中添加按钮 "see more"?

react-native - header 中的 NativeBase (2.0) 更长的字符串

javascript - 如何在 react 中返回html文本变量并打印为html?

javascript - 如何在es6的react模板中使用if和else

reactjs - React Router/Redux/HOC 不适用于 'render' prop