在 redux 中在哪里调度多个操作? [英] Where to dispatch multiple actions in redux?

查看:50
本文介绍了在 redux 中在哪里调度多个操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用带有 connectredux-thunk 中间件和容器的 redux.

I am using redux with connect and redux-thunk middleware and containers.

当前,当用户执行一个操作时,例如单击一个按钮,我需要调度该操作(同步),它将调度其他几个操作(异步).

Currently when an user perform an action, example one click on a button, I need to dispatch that action (sync) which will dispatch other few actions (asynch).

我知道从 reducer 内部调度 action 是一种反模式.

I am aware dispatching actions from within the reducer is an anti pattern.

我想知道这段代码的合适位置.

I would like to know what is a suitable place for this code.

目前我不确定它是否应该留在:

Currently I am not sure if it should stay in:

  • 动作创建者.
  • 在容器中使用 store.subscribe.

推荐答案

根据 文档 位于动作创建者中,如下所示:

The recommended way as per the documentation is in the action creator, like so:

function actionCreator(payload) {
    return dispatch => {
        dispatch(action1(payload))
        dispatch(action2(payload))
    }
}

然后,您可能希望将动作创建者作为道具附加并使用 mapDispatchToProps 将其传递给容器,就像提到的示例 这里.所以它看起来像这样:

Then you would probably want to attach the action creators as prop and pass it down to the container using mapDispatchToProps like in the example mentioned here. So it would look something like so:

const mapDispatchToProps = dispatch => ({
   action1: some_payload => dispatch(action1(some_payload))
   action2: some_payload => dispatch(action2(some_payload))
})

// your component
export default connect(mapStateToProps, mapDispatchToProps)(YourApp)

这篇关于在 redux 中在哪里调度多个操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆