在分派其他特定操作之后分派一个操作,并由于前两个操作而等待状态更改

时间:2018-08-14 17:11:34

标签: reactjs redux redux-thunk

我正尝试在其他两个动作被调度 之后调度一个动作,由于这些动作,状态已更改。我已经读过redux-saga,但我真的很希望在没有可能的情况下做到这一点(当前,我们正在使用redux-thunk)。

我正在采用与Dan Abramov在这里提出的类似方法:https://github.com/reduxjs/redux/issues/723#issuecomment-139927639

操作以正确的顺序执行,但是then()内部的操作是在之前执行的,这是由于firstActionDispatcher改变了状态的函数。 >

我正在使用promise.all都使用下一种方法:

export const getData = categoryId => (dispatch, getState) => {
    const state = getState();
    const elements = state.categories && state.categories.elements && state.categories.elements[categoryId];

    if (elements && elements.withMetadata) {
        return false;
    }

    return Promise.all([
        dispatch(firstActionDispatcher(categoryId)),
        dispatch(secondActionDispatcher)
    ])
    .then(() => dispatch({ type: THIRD_ACTION, data: Id }))
    .catch(error => window.newrelic.noticeError(new Error(`[Error] ${error}`)));
};

更新说明1: firstActionDispatcher返回的承诺与secondActionDispatcher相同,

我已经为此苦苦挣扎了几天。

1 个答案:

答案 0 :(得分:0)

如果您查看的是您提供的代码段,那么您将这样做:

return Promise.all([
    dispatch(firstActionDispatcher(categoryId)),
    dispatch(secondActionDispatcher)
])
.then(() => dispatch({ type: THIRD_ACTION, data: Id }))

请注意,secondActionDispatcher没有被调用。我不确定这是否是错字,但您可能应该这样做:

return Promise.all([
    dispatch(firstActionDispatcher(categoryId)),
    dispatch(secondActionDispatcher())           // Notice the function call
])
.then(() => dispatch({ type: THIRD_ACTION, data: Id }))
相关问题