【问题标题】:dispatching inside actions in action creator在动作创建者中调度内部动作
【发布时间】:2018-11-23 10:13:53
【问题描述】:

我们可以在 action creators 中使用 dispatch 吗?它们在 action creators 中服务的目的是什么? 这是来自代码库的示例修改代码。

export default function xyz(data) {
    const url = ;
    return function (dispatch) {
        dispatch(
            a()
        );
        callApi(url, REQUESTS.POST, HEADERS, data).then((response) =>{
            dispatch(
                b(data)
            );
        }).catch((error) => {
            dispatch(
                c(error.toString())
            );
        });
    };
}
// this returns  a type (an object) 
export function a() {
    return {
        type: xyzzzz
    };
}
Similarly we have b and c returning either type or say objects .

【问题讨论】:

    标签: redux react-redux


    【解决方案1】:

    是的,您可以在一个动作中分派多个动作。

    我通常对这样的异步操作进行调度

    function action() => {
      return async (dispatch) => {
        let payload;
    
        dispatch('before-request');
        try {
          await someAsyncProcess();
          payload = { status: 'success' };
        } catch (err) {
          payload = { status: 'failure' };
        }
        dispatch('after-request', payload);
      };
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-31
      • 2019-01-08
      • 2019-08-14
      • 2015-10-01
      • 2018-03-18
      相关资源
      最近更新 更多