【问题标题】:How to wait for a different epic to finish and the store to be updated, before starting another epic with redux-observables?在使用 redux-observables 开始另一个史诗之前,如何等待不同的史诗完成并更新商店?
【发布时间】:2021-05-24 07:32:48
【问题描述】:

在我的场景中,当应用加载时,我调度了一个启动史诗的操作以创建一个 API 实例,这是进行其他 API 调用所必需的:

const connectApiEpic: Epic = (action$, state$) =>
  action$.pipe(
    ofType('CONNECT_API'),
    mergeMap(async (action) => {
      const sdk = await AppApi.connect({ url: apiUrl });

      return { type: 'SET_API', payload: api };
    })
  );

UI 已加载,API 连接在后台进行。现在如果用户点击某个搜索按钮,我必须调度另一个动作(史诗)来执行搜索,这需要 API 已经连接。

基本上,我需要执行以下操作:

const searchItem: Epic = (action$, rootState$) =>
  action$.pipe(
    ofType('SEARCH_ITEM'),
    mergeMap(async (action) => {
      const { api } = rootState$.value;

      const item = await api.search(action.item);

      return { type: 'SET_ITEM', payload: item };
    })
  );

但是,在从connectApiEpic 在商店中设置 API 之前,这将不起作用。

使用 redux-observables 和 rxjs,怎么可能:

  1. 应用启动时连接api,在后台(已经soloved)
  2. 如果用户点击“搜索”,则派发一个epic进行搜索,但要先等待api连接,或者如果api已经连接,则继续搜索

【问题讨论】:

    标签: reactjs redux rxjs redux-observable redux-toolkit


    【解决方案1】:

    所以,如果api 是你需要在searchItem 史诗中等待的东西,我认为这将是一种方法:

    const searchItem: Epic = (action$, rootState$) =>
      action$.pipe(
        ofType('SEARCH_ITEM'),
    
        mergeMap(
          // waiting for the api to connect first
          // if it's already there, everything will happen immediately
          action => rootState$.pipe(
            map(state => state.api)
            filter(api => !!api),
          ),
        ),
    
        mergeMap(
          api => from(api.search(action.item)).pipe(
            map(item => ({ type: 'SET_ITEM', payload: item }))
          )
        )
      );
    

    【讨论】:

    • 效果很好,我没想到要使用rootState$ 流!谢谢。不过有一件事,我必须把最后一个mergeMap 移到rootState$ 管道中,否则action 将不可用
    猜你喜欢
    • 2019-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-06
    相关资源
    最近更新 更多