我正在使用 redux 中的 applyMiddleware ,它将中间件作为参数,并且我已经传递了 thunk 但不知何故我无法解决与中间件不是函数相关的问题。
下面是我的代码片段。在此代码中,我尝试将 redux thunk 传递给 applyMiddleware
import Redux from 'redux'
const { createStore, applyMiddleware } = Redux;
import thunk from 'redux-thunk';
const initialState = {
loading: false,
users: [],
error: '',
}
const FETCH_USERS_REQUESTED = 'FETCH_USERS_REQUESTED'
const FETCH_USERS_SUCCEEDED = 'FETCH_USERS_SUCCEEDED'
const FETCH_USERS_FAILED = 'FETCH_USERS_FAILED'
这是我的动作创作者。
const fetchUsersRequest = () =>{
return{
type: FETCH_USERS_REQUESTED,
}
}
const fetchUsersSuccess = (users) =>{
return{
type: FETCH_USERS_SUCCEEDED,
payload: users,
}
}
const fetchUserFailure = (error) =>{
return{
type: FETCH_USERS_FAILED,
payload: error,
}
}
这是我的减速机
const reducer = (state = initialState, action) =>{
switch(action.type)
{
case FETCH_USERS_REQUESTED:
return{
...state,
loading: true,
}
case FETCH_USERS_SUCCEEDED:
return{
...state,
loading: false,
users: action.payload,
error: ''
}
case FETCH_USERS_FAILED:
return{
...state,
loading: false,
users: [],
error: action.payload,
}
}
}
我正在尝试创建商店
const store = createStore(reducer, applyMiddleware(thunk));
我收到的错误如下
return middleware(middlewareAPI);
^
TypeError: middleware is not a function
at D:\CDAC_2022\WPT\HarryReact\Codvelution-Redux\REDUX-DEMO\node_modules\redux\lib\redux.js:703:16
at Array.map (<anonymous>)
at D:\CDAC_2022\WPT\HarryReact\Codvelution-Redux\REDUX-DEMO\node_modules\redux\lib\redux.js:702:31
at createStore (D:\CDAC_2022\WPT\HarryReact\Codvelution-Redux\REDUX-DEMO\node_modules\redux\lib\redux.js:162:33)
at file:///D:/CDAC_2022/WPT/HarryReact/Codvelution-Redux/REDUX-DEMO/asyncActions.js:62:15
at ModuleJob.run (node:internal/modules/esm/module_job:217:25)
at async ModuleLoader.import (node:internal/modules/esm/loader:316:24)
at async loadESM (node:internal/process/esm_loader:34:7)
at async handleMainPromise (node:internal/modules/run_main:66:12)
Node.js v20.9.0
const thunkMiddleware = require('redux-thunk').default;已经过时了。使用这个代替: const thunkMiddleware = require('redux-thunk').thunk;
和平。