如何向Redux添加多个中间件?

时间:2017-05-13 16:03:30

标签: reactjs redux react-redux middleware redux-thunk

我已经插入了一个中间件,redux-thunk,我想添加另一个redux-logger。

如何配置它以便我的应用程序使用两个中间件?我尝试传递一个[ReduxThunk, logger]数组,但是没有用。

代码:

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import ReduxThunk from 'redux-thunk';
import logger from 'redux-logger';

import App from './components/app';
import reducers from './reducers';
require('./style.scss');

const createStoreWithMiddleware = applyMiddleware(ReduxThunk)(createStore);

ReactDOM.render(
  <Provider store={createStoreWithMiddleware(reducers)}>
    <App />
  </Provider>,
  document.querySelector('#app')
);

5 个答案:

答案 0 :(得分:69)

applyMiddleware将每个中间件作为新参数(不是数组)。所以只需传入你想要的每个中间件。

const createStoreWithMiddleware = applyMiddleware(ReduxThunk, logger)(createStore);

答案 1 :(得分:15)

安迪的答案很好, 但是,考虑一下你的中间件在增长, 以下代码会更好:

const middlewares = [ReduxThunk, logger]
applyMiddleware(...middlewares)

答案 2 :(得分:7)

applyMiddleware应该作为第二个参数传递给createStore。 applyMiddleware可以有多个中间件作为参数。

const store = createStore(reducers, applyMiddleware(ReduxThunk, logger));

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.querySelector('#app')
);

答案 3 :(得分:0)

这是应用一种或多种中间件的方法:

import {createStore, applyMiddleware} from 'redux';
import thunk from 'redux-thunk';
import logger from 'redux-logger';
import {rootReducer} from "../reducers"; // Import your combined reducers ;)

const middleWares = [thunk, logger]; // Put the list of third part plugins in an array 

// Create the store with the applied middleWares and export it
export const store = createStore(rootReducer, applyMiddleware(...middleWares));

现在将最近导出的商店导入到index.js中,并将其传递给Provider组件。 您的index.js文件应如下所示:

... ...

import {Provider} from 'react-redux';
import {store} from './store';

ReactDOM.render(
    <Provider store={store}>
        <App />
    </Provider>, 
document.getElementById('root'));

仅此而已!

答案 4 :(得分:0)

答案可能有点晚了,但是我的问题是在中间件中添加了devtools,希望这对某人有帮助

 // imports.. 
 import { composeWithDevTools } from "redux-devtools-extension";

  const store = createStore(
     Reducer,
     persistedState,
    composeWithDevTools(applyMiddleware(ReduxThunk, promiseMiddleware))
 );