gpt4 book ai didi

redux-observable - 如何在单个Redux可观察的史诗中等待/屈服于多个 Action ?

转载 作者:行者123 更新时间:2023-12-04 04:09:56 25 4
gpt4 key购买 nike

我有一个redux Saga,每次发送“WATCHLIST_FETCH_REQUEST”时,它都会运行三种不同的 Action :

function* watchFetchWatchlist() {
yield takeLatest('WATCHLIST_FETCH_REQUEST', fetchWatchlist);
}


function* fetchWatchlist() {
const activity = 'ACTIVITY_FETCH_WATCHLIST';
yield put(
addNetworkActivity(activity) // Action 1: enables a global loading indicator before request is made
);
const { response, error } = yield call(
api.fetchWatchlist // make an API request
);
yield put(
removeNetworkActivity(activity) // Action 2: removes the above global loading indicator after request completes
);
if (response) {
yield put(
updateUserWatchlist(response) // Action 3a: updates Redux store with data if response was successful
);
} else {
yield put(
watchlistFetchFailed(error) // Action 3b: updates Redux store with error if response failed
);
}
}

这个传奇的流程本质上是同步的。必须首先运行操作1才能设置应用程序的全局加载状态。当网络事件完成时,操作2必须在操作1之后并且在API响应返回之后才能运行,以删除全局加载状态。

我对redux-observable还是很陌生,但是我一直在努力探索如何将这个传奇转化为史诗。这里有两个目标:
  • 依次执行操作,而不是并行运行
  • 在单个史诗中执行这些操作/流程(触发类型:'WATCHLIST_FETCH_REQUEST'时会踢开)

  • 您如何通过redux-observable实现此目标?谢谢!

    最佳答案

    我在这里将部分对话拼凑在一起,从而找到了问题的答案:https://github.com/redux-observable/redux-observable/issues/62

    我最终得到了一些类似的东西:

    import { concat as concat$ } from 'rxjs/observable/concat';
    import { from as from$ } from 'rxjs/observable/from';
    import { of as of$ } from 'rxjs/observable/of';


    export const fetchWatchlistEpic = (action$) => {
    const activity = 'ACTIVITY_FETCH_WATCHLIST';

    return action$.ofType('WATCHLIST_FETCH_REQUEST')
    .switchMap(() =>
    concat$(
    of$(addNetworkActivity(activity)),
    from$(api.fetchWatchlist())
    .map((data) => Immutable.fromJS(data.response))
    .switchMap((watchlist) =>
    of$(
    updateUserWatchlist(watchlist),
    removeNetworkActivity(activity),
    )
    )
    )
    );
    };

    尝试顺序运行多个操作时, concatof似乎是首选操作符。

    关于redux-observable - 如何在单个Redux可观察的史诗中等待/屈服于多个 Action ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42034325/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com