类型错误:中间件不是函数

IT技术 reactjs redux react-redux redux-thunk
2021-05-10 14:31:15

我正在尝试在我的 reactjs 应用程序中应用 redux。由于这些错误,我无法继续:

在此处输入图片说明

在此处输入图片说明

我确定我已经安装了我需要的所有依赖项。这是我的 package.json 的相关部分

"dependencies": {
   "react-redux": "^5.0.6",
   "redux": "^3.7.2",
   "redux-logger": "^3.0.6",
   "redux-promise": "^0.5.3",
   "redux-thunk": "^2.2.0",
}

这是实现 redux 的 index.js 的一部分

import { createStore, applyMiddleware } from 'redux';
import { Provider } from 'react-redux';
import thunkMiddleware from 'redux-thunk';
import createLogger from 'redux-logger';
import reducers from './reducers';

const logger = createLogger();
const store = createStore(reducers,
    applyMiddleware(
        thunkMiddleware, logger
    )
)

ReactDOM.render(
    <Provider store={store}>
        <App />
    </Provider>,
    document.getElementById('root')
);
4个回答

根据文档,您正在混淆使用redux-logger

您要么需要导入特定createLogger功能

import { createLogger } from 'redux-logger'

const logger = createLogger({
  // ...options
});

或者使用默认导入

import logger from 'redux-logger'

然后你的代码应该没问题

const store = createStore(
  reducers,
  applyMiddleware(thunkMiddleware, logger)
)
import logger from 'redux-logger';
import thunk from 'redux-thunk';
import reduxPromiseMiddleware from 'redux-promise-middleware';
import { applyMiddleware, createStore } from 'redux';

const middleware = applyMiddleware(reduxPromiseMiddleware, thunk, logger);
const store = createStore(reducer, middleware);

我在您的依赖项中没有看到 react 和 react-dom,它也不包含在导入语句中。

让我为您提供一个示例,说明我最近如何做一个应用程序,还使用了令人惊叹的 redux 开发人员工具。

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, combineReducers, applyMiddleware, compose } from 'redux';
import reduxThunk from 'redux-thunk';
import App from './components/App';
import authReducer from '../reducers/auth';
import urlsReducer from '../reducers/urls';

const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;

//Store creation
  const store = createStore(
    combineReducers({
      auth: authReducer,
      urls: urlsReducer
    }),
    composeEnhancers(applyMiddleware(reduxThunk))
  );

ReactDOM.render(
      <Provider store={store}>
        <App />
      </Provider>,
      document.getElementById('root')
    );

我认为你只需要在 reduxThunk 之后添加记录器。如果你已经组合了你的减速器,那么只需提供减速器而不是 combineReducers。

问候, 拉斐尔

我收到了同样的错误TypeError: middleware is not a function

import { createStore, combineReducers, applyMiddleware } from "redux";
import { createLogger } from "redux-logger";
import thunk from "redux-thunk";

import math from "./reducers/mathReducer";
import user from "./reducers/userReducer";

const logger = createLogger();

export default createStore(
  combineReducers({ math, user }),
  {},
  applyMiddleware(logger, thunk)
);

更换applyMiddleware(logger, thunk)applyMiddleware(logger, thunk.default)为我工作。