我如何在Redux-observable中使用“ of”

时间:2018-08-28 15:08:37

标签: reactjs redux-observable

我是Redux-Observable的新手。因此,我在项目中应用了redux-observable,并且希望通过redux-observable调度操作,因此我使用了“ of”(就像之前RXJS版本中的Observable.of()一样)。但是我收到的答复是“动作必须是简单的对象。对异步动作使用自定义中间件”。我设置的史诗中间件或代码有问题吗?

store.js

import { createStore, applyMiddleware, compose } from 'redux';
import { createEpicMiddleware } from 'redux-observable';
import { rootEpic } from './epics';
import reducers from './reducers';

const epicMiddleWare = createEpicMiddleware();
const configureStore = () => {
  const store = createStore(
    reducers,
    compose(
      applyMiddleware(epicMiddleWare),
      window.devToolsExtension ? window.devToolsExtension() : (f) => { return f; },
    ),
  );

  epicMiddleWare.run(rootEpic);

  return store;
};

export default configureStore;

epic.js

export const fetchNavigationEpic = (action$) => {
  return action$
    .ofType(actionTypes.FETCH_NAVIGATION_LIST)
    .pipe(
      mergeMap(() => {
        return from(CreateService(SettingService).getAll())
          .pipe(
            map((response) => {
              if (response.status === 200) {
                return of(fetchNavigationSuccess(response));
              }

              return fetchNavigationFailed(response);
            }),
          );
      }),
    );
};

action.js

export const fetchNavigation = { type: actionTypes.FETCH_NAVIGATION_LIST };
export const fetchNavigationSuccess = (payload) => {
  return { type: actionTypes.FETCH_NAVIGATION_LIST_SUCCESS, payload };
};
export const fetchNavigationFailed = (payload) => {
  return { type: actionTypes.FETCH_NAVIGATION_LIST_FAILED, payload };
};

图书馆信息:  “ redux-observable”:“ ^ 1.0.0”,  “ rxjs”:“ ^ 6.2.1”,  “ rxjs-compat”:“ ^ 6.2.1”,

1 个答案:

答案 0 :(得分:1)

问题在于您返回的是流,而不是操作。

如果返回可观察的(of(yourAction)),则需要使用mergeMap来使它变平

如果您要返回操作,则可以使用map代替mergeMap

要么是

export const fetchNavigationEpic = (action$) => {
  return action$
    .ofType(actionTypes.FETCH_NAVIGATION_LIST)
    .pipe(
      mergeMap(() => {
        return from(CreateService(SettingService).getAll())
          .pipe(
            mergeMap((response) => {
              if (response.status === 200) {
                return of(fetchNavigationSuccess(response));
              }

              return of(fetchNavigationFailed(response));
            }),
          );
      }),
    );
};

export const fetchNavigationEpic = (action$) => {
      return action$
        .ofType(actionTypes.FETCH_NAVIGATION_LIST)
        .pipe(
          mergeMap(() => {
            return from(CreateService(SettingService).getAll())
              .pipe(
                map((response) => {
                  if (response.status === 200) {
                    return fetchNavigationSuccess(response);
                  }

                  return fetchNavigationFailed(response);
                }),
              );
          }),
        );
    };