【问题标题】:Dispatch an action after other specific actions were dispatched and wait for state to change because of the first two actions在调度其他特定动作后调度一个动作,并等待状态因前两个动作而改变
【发布时间】:2018-08-14 17:11:33
【问题描述】:

我正在尝试在其他两个动作被调度后调度一个动作并且状态因为这些动作而改变。我已经阅读了有关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 也是如此,

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

【问题讨论】:

  • 动作是根据github.com/reduxjs/redux/issues/1199 同步调度的——所以你不能在其他两个动作之后调度第三个动作吗? (摆脱 Promise)
  • firstActionDispatcher 正在返回一个承诺,对于 secondActionDispatcher 也是如此,他们正在获取数据,这就是我使用 Promise.all 的原因。 @TrueWill 我会更新问题以反映这一点。
  • 我知道我迟到了,但也许你应该从这些承诺中返回一些价值?在您提供的 Github 页面上 - 当前两个操作没有返回 fetch 时发生同样的情况,而只是调用它

标签: reactjs redux redux-thunk


【解决方案1】:

如果您查看您提供的代码的 sn-p,您正在这样做:

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 }))

【讨论】:

  • 它被正确调用并调用了函数,我们使用的是来自商店的dispatch()方法,基本上dispatch(secondActionDispatcher)secondActionDispatcher(dispatch, state)是一样的。 @tpdietz
猜你喜欢
  • 2020-04-23
  • 1970-01-01
  • 2017-04-18
  • 2018-09-28
  • 2016-10-24
  • 1970-01-01
  • 2012-11-25
  • 1970-01-01
  • 2017-05-14
相关资源
最近更新 更多