本文介绍了在 mapDispatchToProps 中使用 thunk的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何在 mapDispatchToProps 中为 react-reduxconnect 使用异步动作创建器.我正在使用 redux-thunk 中间件,以下是我的 mapDispatchToProps:

I'm wondering how to use async action creators in mapDispatchToProps for react-redux's connect. I'm using the redux-thunk middleware and the following is my mapDispatchToProps:

function mapDispatchToProps(dispatch) {
    return {
        foo: function() {
            dispatch(someAction());

            return function asyncAction(dispatch, getState) {
                console.log("An async action!");
                dispatch(someOtherAction(getState().foo));
            };
        }
    }
}

但是,当我执行上述操作时,不会执行异步操作.这样做的正确方法是什么?

However, when I do the above, the async action does not get executed. What is the correct way to do this?

推荐答案

我建议以不同的方式声明您的实际 thunk (someOtherAction).在以下示例中,asyncAction 是一个异步操作创建器,它返回一个 thunk.然后 thunk 可以分派其他操作(例如,在 promise 解决之后).

I suggest declaring your actual thunk (someOtherAction) differently. In the following example, asyncAction is an async action creator which returns a thunk. The thunk can then dispatch other actions (after a promise resolves for example).

function asyncActionCreator () {
  return (dispatch, getState) => {
    dispatch(someAction());

    someAsyncStuff().then(() => {
      dispatch(someOtherAction(getState().foo);
    });
  }
}

function mapDispatchToProps(dispatch) {
  return {
    foo: () => dispatch(asyncActionCreator())
  }
}

这篇关于在 mapDispatchToProps 中使用 thunk的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-16 06:43