【问题标题】:TypeError: getState is not a function when adding middleware to ReduxTypeError: 向 Redux 添加中间件时 getState 不是函数
【发布时间】:2016-08-19 21:15:32
【问题描述】:

在我的 configureStore.dev.js 文件中使用此代码,我在添加 applyMiddleware(reduxImmutableStateInvariant) 时得到一个 Uncaught TypeError: getState is not a function。当我删除这个添加的中间件时,我的项目运行良好。添加此中间件的正确方法是什么?这是完整的文件:

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;
}

【问题讨论】:

    标签: javascript reactjs redux middleware


    【解决方案1】:

    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 redux@>=3.1.0
    const store = createStore(
      reducer,
      applyMiddleware(...middleware)
    );
    

    为什么 thunk 不是一个函数呢?

    thunk 中间件中,thunk 函数为called before it is returned

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

    那么为什么 redux-immutable-state-invariant 是一个函数呢?

    根据代码,您似乎可以传入一个函数 (isImmutable),该函数用于确定您的 redux 状态中的哪些属性是不可变的。我认为提供你自己的 isImmutable 函数可以让这个中间件与其他不可变库很好地协同工作。

    export default function immutableStateInvariantMiddleware(isImmutable = isImmutableDefault) {
    

    这里使用了那个方法 https://github.com/leoasis/redux-immutable-state-invariant/blob/5ed542246e32b7eec06879b25e5a0a478daf4892/src/trackForMutations.js#L5

    【讨论】:

      猜你喜欢
      • 2018-01-31
      • 2017-09-24
      • 2020-08-18
      • 2019-07-06
      • 2018-04-02
      • 2018-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多