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

我已经插入了一个中间件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')
);
4个解决方案
88 votes

applyMiddleware将每个中间件作为新参数(而不是数组)。 因此,只需传入您想要的每个中间件即可。

const createStoreWithMiddleware = applyMiddleware(ReduxThunk, logger)(createStore);
Andy Noelker answered 2019-11-15T11:31:08Z
18 votes

安迪的答案很好,但是,考虑到您的中间件正在增长,下面的代码会更好:

const middlewares = [ReduxThunk, logger]
applyMiddleware(...middlewares)
chen Jacky answered 2019-11-15T11:31:35Z
8 votes

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

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

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.querySelector('#app')
);
Tharaka Wijebandara answered 2019-11-15T11:32:00Z
0 votes

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

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'));

就这样 !

MUSTAPHA GHLISSI answered 2019-11-15T11:32:45Z
translate from https://stackoverflow.com:/questions/43955199/how-to-add-multiple-middleware-to-redux