2016-08-19 48 views
4

在我的configureStore.dev.js文件中使用此代碼時,在添加applyMiddleware(reduxImmutableStateInvariant)時,我得到一個Uncaught TypeError: getState is not a function。當我刪除這個添加的中間件時,我的項目運行良好。什麼是添加這個中間件的正確方法?以下是完整的文件:TypeError:將中間件添加到Redux時,getState不是函數

import {createStore, compose, applyMiddleware} from 'redux'; 
import rootReducer from '../reducers'; 
import reduxImmutableStateInvariant from 'redux-immutable-state-invariant'; 

export default function configureStore(initialState) { 
    const store = createStore(rootReducer, initialState, compose(
    // Add other middleware on this line... 
    applyMiddleware(reduxImmutableStateInvariant), 
    window.devToolsExtension ? window.devToolsExtension() : f => f // add support for Redux dev tools 
    ) 
); 

    if (module.hot) { 
    // Enable Webpack hot module replacement for reducers 
    module.hot.accept('../reducers',() => { 
     const nextReducer = require('../reducers').default; // eslint-disable-line global-require 
     store.replaceReducer(nextReducer); 
    }); 
    } 

    return store; 
} 

回答

10

reduxImmutableStateInvariant是,你需要傳遞到applyMiddleware之前調用的函數。

const store = createStore(rootReducer, initialState, compose(
     // Add other middleware on this line... 
     applyMiddleware(reduxImmutableStateInvariant()), 
     window.devToolsExtension ? window.devToolsExtension() : f => f // add support for Redux dev tools 
    ) 
); 

這哪裏是在文檔?

在github中README docs,被調用後被導入(通過require)reduxImmutableStateInvariant。見第三行,如下:

// Be sure to ONLY add this middleware in development! 
const middleware = process.env.NODE_ENV !== 'production' ? 
    [require('redux-immutable-state-invariant')(), thunk] : 
    [thunk]; 

// Note passing middleware as the last argument to createStore requires [email protected]>=3.1.0 
const store = createStore(
    reducer, 
    applyMiddleware(...middleware) 
); 

爲什麼不咚的功能有關係嗎?

在thunk中間件中,thunk功能是called before it is returned

const thunk = createThunkMiddleware(); 
thunk.withExtraArgument = createThunkMiddleware; 

export default thunk; 

那麼,爲什麼是終極版,不變的狀態不變的功能?

根據代碼,它看起來像你可以傳入一個函數(isImmutable),用於確定你的redux狀態中哪些屬性是不可變的。我認爲提供你自己的isImmutable功能可以讓這個中間件很好地與其他不可變的庫一起工作。

export default function immutableStateInvariantMiddleware(isImmutable = isImmutableDefault) { 

這種方法用在這裏 https://github.com/leoasis/redux-immutable-state-invariant/blob/5ed542246e32b7eec06879b25e5a0a478daf4892/src/trackForMutations.js#L5

相關問題