如何异步添加史诗?

时间:2018-08-01 11:46:05

标签: reactjs redux redux-observable rxjs6

我能够添加异步减速器,但无法添加异步史诗

在链接Adding New Epics Asynchronously之后,我尝试使用epic$.next(),但是无法添加新的史诗。

import { applyMiddleware, createStore, compose } from 'redux';
import { createEpicMiddleware, combineEpics } from 'redux-observable';
import { BehaviorSubject } from 'rxjs';
import { mergeMap } from 'rxjs/operators';
import createReducer from '../reducers';
import mainEpic from '../config/epics';

中间件配置如下:

const epicMiddleware = createEpicMiddleware();

const epic$ = new BehaviorSubject(mainEpic);
const rootEpic = (action$, state$) =>
  epic$.pipe(mergeMap(epic => epic(action$, state$)));

用于Redux开发工具的商店增强器

const composeEnhancers =
  // compose;
  process.env.NODE_ENV === 'development' &&
  window.navigator.platform !== 'iPad' &&
  window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__
    ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__
    : compose;

这是商店的实例

export default () => {
  const store = createStore(
    createReducer(),
    composeEnhancers(applyMiddleware(epicMiddleware))
  );

  epicMiddleware.run(rootEpic);

  // Extra functionality to the store
  store.asyncReducers = {};

在这里,当新组件被异步绑定时,我用参数keyreducernewEpic调用injectRepics(reducer和epics的复制品)

  store.injectRepics = (key, reducer, newEpic) => {
    if (!store.getState()[key]) {

      // here I get newEpic
      console.log(newEpic);

      // new reducer is added to asyncreducer object
      store.asyncReducers[key] = reducer;
      // new reducer is created and replaced
      store.replaceReducer(createReducer(store.asyncReducers));

      // -------------------------------------
            But, I'm unable to replace epic
      // -------------------------------------
      newEpic && epic$.next(newEpic);

      // epicMiddleware.run(rootEpic);
      // newEpic && addNewEpic(newEpic);
    }
  };

  return store;
};

1 个答案:

答案 0 :(得分:0)

有一个简单的错误。

我忘了在新的史诗中添加CombineEpics。

因此,代码变为newEpic && epic$.next(combineEpics(...newEpic))