5

我无法弄清楚在 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() 作为第三个参数。

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

4

3 回答 3

6

你可以这样做

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;
于 2018-06-07T09:31:09.613 回答
5

compose从 redux使用:

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

// ...

const initialState = { counter: { count:0 } };
const store = compose(
    applyMiddleware(thunk),
    window.devToolsExtension && window.devToolsExtension(),
)(createStore)(reducers, initialState);
于 2018-06-07T09:18:33.250 回答
1

这应该工作得很好 -

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;
于 2020-11-23T01:44:37.623 回答