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

问题描述 投票:0回答:1

我正在学习Redux,所以按照网上资源写了下面的逻辑,但它抛出了这个错误:

/home/sssawant/Sarvesh/notes_fullstack/frontend/React_notes/redux_demo/node_modules/redux/dist/cjs/redux.cjs:407
const chain = middlewares.map((middleware) => middleware(middlewareAPI));

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

在/home/sssawant/Sarvesh/notes_fullstack/frontend/React_notes/redux_demo/node_modules/redux/dist/cjs/redux.cjs:407:51
在Array.map()
在/home/sssawant/Sarvesh/notes_fullstack/frontend/React_notes/redux_demo/node_modules/redux/dist/cjs/redux.cjs:407:31
在createStore(/home/sssawant/Sarvesh/notes_fullstack/frontend/React_notes/redux_demo/node_modules/redux/dist/cjs/redux.cjs:133:33)
在对象。 (/home/sssawant/Sarvesh/notes_fullstack/frontend/React_notes/redux_demo/asyncActions2.js:79:15)
在Module._compile(节点:内部/模块/cjs/loader:1376:14)
在 Module._extensions..js (节点:内部/模块/cjs/loader:1435:10)
在Module.load(节点:内部/模块/cjs/loader:1207:32)
在Module._load(节点:内部/模块/cjs/loader:1023:12)
在 Function.executeUserEntryPoint [作为 runMain] (节点:internal/modules/run_main:135:12)

Node.js v20.11.0

我有以下版本的依赖项。

节点版本 - v20.11.0

当前依赖项

├── [email protected]
[email protected]
[email protected]
[email protected]

我的代码:

const redux = require("redux");
const { thunk } = require("redux-thunk");
const createStore = redux.createStore;
const applyMiddleware = redux.applyMiddleware;
const thunkMiddleware = require("redux-thunk").default
const axios = require("axios");

const initialState = {
  loading: false,
  users: [],
  error: "",
};

const FETCH_USERS_REQUEST = "FETCH_USERS_REQUEST";
const FETCH_USERS_SUCCESS = "FETCH_USERS_SUCCESS";
const FETCH_USERS_FAILURE = "FETCH_USERS_FAILURE";

const fetchUsersRequest = () => {
  return {
    type: FETCH_USERS_REQUEST,
  };
};

const fetchUsersSuccess = (users) => {
  return {
    type: FETCH_USERS_SUCCESS,
    payload: users,
  };
};

const fetchUsersFailure = (error) => {
  return {
    type: FETCH_USERS_FAILURE,
    payload: error,
  };
};

const reducer = (curState, action) => {
  switch (action.type) {
    case FETCH_USERS_REQUEST:
      return {
        ...curState,
        loading: true,
      };

    case FETCH_USERS_SUCCESS:
      return {
        ...curState,
        loading: false,
        users: action.payload,
        error: "",
      };

    case FETCH_USERS_FAILURE:
      return {
        ...curState,
        loading: false,
        users: [],
        error: action.payload,
      };
  }
};

const fetchUsers = () => {
  return function (dispatch) {
    dispatch(fetchUsersRequest());
    axios
      .get("https://jsonplaceholder.typicode.com/users")
      .then((rsponse) => {
        const users = response.data.map((user) => user.id);
        dispatch(fetchUsersSuccess(users));
      })
      .catch((error) => {
        dispatch(fetchUsersFailure(error.message));
      });
  };
};

const store = createStore(reducer, applyMiddleware(thunkMiddleware));
store.subscribe(() => {console.log(store.getState())});
store.dispatch(fetchUsers())

为什么我会收到此错误?是语法错误,还是由于 Node 和 Redux-Thunk 的版本不同?

javascript node.js redux middleware redux-thunk
1个回答
0
投票

readux-thunk@3
中不再有任何
default
导出,因此
require("redux-thunk").default
未定义。

比较 v2

...

const thunk = createThunkMiddleware() as ThunkMiddleware & {
  withExtraArgument<
    ExtraThunkArg,
    State = any,
    BasicAction extends Action = AnyAction
  >(
    extraArgument: ExtraThunkArg
  ): ThunkMiddleware<State, BasicAction, ExtraThunkArg>
}

// Attach the factory function so users can create a customized version
// with whatever "extra arg" they want to inject into their thunks
thunk.withExtraArgument = createThunkMiddleware

export default thunk

v3

...

function createThunkMiddleware<
  State = any,
  BasicAction extends Action = AnyAction,
  ExtraThunkArg = undefined
>(extraArgument?: ExtraThunkArg) {
  // Standard Redux middleware definition pattern:
  // See: https://redux.js.org/tutorials/fundamentals/part-4-store#writing-custom-middleware
  const middleware: ThunkMiddleware<State, BasicAction, ExtraThunkArg> =
    ({ dispatch, getState }) =>
    next =>
    action => {
      // The thunk middleware looks for any functions that were passed to `store.dispatch`.
      // If this "action" is really a function, call it and return the result.
      if (typeof action === 'function') {
        // Inject the store's `dispatch` and `getState` methods, as well as any "extra arg"
        return action(dispatch, getState, extraArgument)
      }

      // Otherwise, pass the action down the middleware chain as usual
      return next(action)
    }
  return middleware
}

export const thunk = createThunkMiddleware()

...

更新您的代码以使用

thunk
而不是未定义的
thunkMiddleware
引用。

const redux = require("redux");
const { thunk } = require("redux-thunk"); // <-- the middleware
const createStore = redux.createStore;
const applyMiddleware = redux.applyMiddleware;
const axios = require("axios");

...

const store = createStore(
  reducer,
  applyMiddleware(thunk) // <-- pass thunk middleware
);
© www.soinside.com 2019 - 2024. All rights reserved.