同时启用 redux-promise 和 redux-saga 中间件似乎会导致问题

Posted

技术标签:

【中文标题】同时启用 redux-promise 和 redux-saga 中间件似乎会导致问题【英文标题】:Enabling both redux-promise and redux-saga middlewares appears to cause problems 【发布时间】:2020-06-20 05:31:38 【问题描述】:

我正在使用弹出的 create-react-app 代码库并尝试设置 redux-saga 和 redux-promise 中间件。然而,无论我如何处理 redux-saga,它似乎都已禁用,或者有时会报告一个错误,表明 applyMiddleware 尚未针对 sagaMiddleware 对象运行。 (请原谅稍微复杂的示例代码。)

import React from 'react';
import ReactDOM from 'react-dom';
import * as serviceWorker from './serviceWorker';

import  Provider  from 'react-redux';
import  createStore, applyMiddleware  from 'redux';
import ReduxPromise from 'redux-promise';
import  Route, BrowserRouter, Switch  from 'react-router-dom';

import reducersP1 from './p1/reducers';
import reducersP2 from './p2/reducers';

import Wrapper from './global/containers/wrapper';
import AppWrap from "./p1/components/app_wrap";
import AppWrap2 from "./p2/containers/app_wrap";

import createSagaMiddleware from 'redux-saga';
import rootSaga from './p2/sagas';

const appConfig = 
  p1: 
    reducers: reducersP1,
    component: AppWrap,
    namespace: "p1",
    api: '/api'
  ,
  p2: 
    reducers: reducersP2,
    component: AppWrap2,
    namespace: "p2",
    api: '/api2'
  
;


const  api, reducers, component, namespace  = process.env.REACT_APP_PORTFOLIO==="1"? appConfig.p1: appConfig.p2;
const WrapComponent = component;
export const apiPath = api;


const sagaMiddleware = createSagaMiddleware();

// Approach A.
const createStoreWithMiddleware = applyMiddleware(sagaMiddleware, ReduxPromise)(createStore);
const store = createStoreWithMiddleware(reducers);

// Approach B.
// const storeWithMiddleware = createStore(
//     reducers,
//     applyMiddleware(sagaMiddleware, ReduxPromise)
// );
// const store = storeWithMiddleware;

sagaMiddleware.run(rootSaga);

ReactDOM.render(
  <Provider store= store >
    <BrowserRouter>
      <Switch>
        <Route path="*" render= (history) => <Wrapper namespace= namespace ><WrapComponent history= history  /></Wrapper>  />
      </Switch>
      </BrowserRouter>
  </Provider>
  ,
  document.getElementById('root')
);

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
serviceWorker.unregister();

【问题讨论】:

【参考方案1】:

似乎 redux-saga 没有正确安装。修正:

yarn add redux-saga

【讨论】:

以上是关于同时启用 redux-promise 和 redux-saga 中间件似乎会导致问题的主要内容,如果未能解决你的问题,请参考以下文章

Reducer 在使用 redux-promise 和 axios 时返回 undefined

使用 React-Router 4 和 Redux-Promise 重定向用户

如何使用 redux 和 redux-promise 将多个 axios 调用合并到一个有效负载中?

redux-promise:未捕获的 TypeError:中间件不是函数

使用 redux-promise 调用 API 时 Redux 状态未更新

使用 redux-promise 处理 redux 错误的正确方法