如何将sagaMiddleWare.run(RootSaga)集成到redux storeFactory中

时间:2018-03-24 20:16:48

标签: reactjs redux react-redux store redux-saga

下面的代码是一个商店工厂,它将根据语句

在命令上创建商店
const store = storeFactory()

我需要将sagaMiddleWare与此storeFactory集成,但我放置代码的任何地方:

sagaMiddleWare.run(RootSaga)

我收到错误:

错误:在运行Saga之前,必须使用applyMiddleware在商店中安装Saga中间件

如何将sagaMiddleWare.run(RootSaga)集成到storeFactory?

"use strict";

import { createStore, combineReducers, applyMiddleware } from "redux";
import createSagaMiddleware from "redux-saga";
import { user, venues, isFetching } from "./reducers";
import stateData from "./initialState.json";
import RootSaga from "./sagas";

const logger = store => next => action => {
  let result;
  console.groupCollapsed("dispatching", action.type);
  console.log("prev state", store.getState());
  console.log("action", action);
  result = next(action);
  console.log("next state", store.getState());
  console.groupEnd();
  return result;
};

const saver = store => next => action => {
  let result = next(action);
  localStorage["redux-store"] = JSON.stringify(store.getState());
  return result;
};

const sagaMiddleWare = createSagaMiddleware();

const storeFactory = (initialState = stateData) =>
  applyMiddleware(logger, saver, sagaMiddleWare)(createStore)(
    combineReducers({ user, venues, isFetching }),
    localStorage["redux-store"]
      ? JSON.parse(localStorage["redux-store"])
      : stateData
  );

export default storeFactory;

1 个答案:

答案 0 :(得分:0)

这里出现错误,似乎表明saga中间件没有正确地加载到商店中。

/* eslint-disable no-underscore-dangle */
    const sagaMiddleware = createSagaMiddleware();
    const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION__ || compose;
    const store = createStore(
        reducers,
        initialState,
        composeEnhancers(applyMiddleware(sagaMiddleware)),
      );
    sagaMiddleware.run(sagas);
/* eslint-enable */

The final code of this tutorial is located in the sagas branch. Then in the .... Now we only have to invoke sagaMiddleware.run on the root Saga in main.js .
https://redux-saga.js.org/docs/introduction/BeginnerTutorial.html