在React-Redux Store中配置devToolsExtension和applyMiddleware()

时间:2018-06-07 09:08:16

标签: javascript reactjs redux react-redux redux-devtools-extension

我无法弄清楚在redux商店中同时使用devToolsExtension和中间件的确切方法。

以下是我的redux商店代码。

import {createStore, combineReducers, applyMiddleware} from 'redux';
import thunk from 'redux-thunk';
import counterReducer from './../reducers/counterReducer';

const reducers = combineReducers({
    counter: counterReducer
});
const store = createStore(
    reducers, 
    {counter: {count:0} },
    // window.devToolsExtension && window.devToolsExtension(), 
    applyMiddleware(thunk)
);

export default store;

由于createStore()需要3个参数。 在应用中间件thunk之前,我使用它作为下面的代码,对我来说很好。

const store = createStore(
    reducers, 
    {counter: {count:0} },
    window.devToolsExtension && window.devToolsExtension()
);

现在,我需要使用devToolsExtension以及同时应用中间件。

我尝试将devToolsExtension和applyMiddleware放在数组中,以便它充当第三个参数,但这不会起作用。

const store = createStore(
    reducers, 
    {counter: {count:0} },
    [window.devToolsExtension && window.devToolsExtension(), 
    applyMiddleware(thunk)]
);

现在的情况是我需要使用devToolsExtension作为第三个参数或者applyMiddleware()作为第三个参数。

但我想同时使用两者。 我怎样才能做到这一点?

3 个答案:

答案 0 :(得分:4)

使用redux的compose

import { 
    compose,
    // ...
} from 'redux';

// ...

const initialState = { counter: { count:0 } };
const store = compose(
    applyMiddleware(thunk),
    window.devToolsExtension && window.devToolsExtension(),
)(createStore)(reducers, initialState);

答案 1 :(得分:2)

你可以这样做

import { createStore, applyMiddleware,compose } from 'redux';
import reducers from '../reducers';
import reduxThunk from 'redux-thunk';
import {signOut} from '../actions/signOut';
import {checkLoggedInState} from '../actions/signIn';
//For Dev Tools -todo =remove for production bundle
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
// const createStoreWithMiddleware=applyMiddleware()(createStore);

const store=createStore(reducers,composeEnhancers(
    applyMiddleware(reduxThunk,signOut,checkLoggedInState)
));
export default store;

答案 2 :(得分:0)

这应该工作得很好-

import { createStore, applyMiddleware, compose } from 'redux';
import rootReducer from '../reducers/rootReducer';
import captureMiddleWare from '../captureMiddleWare';

const commonStore = createStore(rootReducer, compose(applyMiddleware(captureMiddleWare), window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()));

export default commonStore;