我尝试使用createAction函数,但遇到以下错误:
Uncaught Error: Actions may not have an undefined "type" property. Have you misspelled a constant?
我不知道为什么我会得到这个,但我假设它与中间件有关,但我也尝试过添加,它仍然不会工作。
这是我的商店的样子:
import { combineReducers, applyMiddleware, compose } from "redux";
import { configureStore } from "@reduxjs/toolkit";
import { routerMiddleware } from "react-router-redux";
import thunk from "redux-thunk";
import { apiMiddleware } from "redux-api-middleware";
import Immutable from "immutable";
import moduleReducers from "./reducers";
import routerReducer from "./reactRouterReducer";
export default function createStore(history, initialState) {
const middlewares = [thunk, apiMiddleware, routerMiddleware(history)];
const enhancers = compose(applyMiddleware(...middlewares));
const reducer = combineReducers({
router: routerReducer,
...moduleReducers,
});
const preLoadedState = Immutable.fromJS(initialState || {});
return configureStore({
reducer,
preLoadedState,
enhancers,
});
}
这是我的减速器的样子:
import { createAction } from "redux-api-middleware";
import { createSelector } from "reselect";
import deep from "deep-get-set";
import config from "../config/config";
const SET_PROJECT = "SET_PROJECT";
const SET_PROJECTS = "SET_PROJECTS";
const SET_LOADING = "SET_LOADING";
const SET_ERROR = "SET_ERROR";
const initialState = {
isLoading: false,
hasError: false,
user_projects: null,
project: null,
};
export const fetchProjectsList = () =>
createAction({
endpoint: `${config?.apiHost}/projects`,
method: "GET",
headers: [],
credentials: "include",
types: [SET_LOADING, SET_PROJECTS, SET_ERROR],
});
export default function reducer(state = initialState, action) {
switch (action.type) {
case SET_PROJECT: {
const newState = {
...state,
isLoading: false,
hasError: false,
project: action?.project,
};
return newState;
}
case SET_PROJECTS: {
const newState = {
...state,
isLoading: false,
hasError: false,
user_projects: action?.payload,
};
return newState;
}
case SET_LOADING: {
const newState = {
...state,
isLoading: true,
hasError: false,
project: action?.project,
};
return newState;
}
case SET_ERROR: {
const newState = {
...state,
isLoading: false,
hasError: true,
project: action?.project,
};
return newState;
}
default:
return state;
}
}
我试过用不同的redux版本以各种方式设置我的商店,但仍然得到同样的错误。有趣的是,我用了这个完全相同的函数作为一个类,并能够成功地使用它,但出于某种原因,我不知道为什么现在它不工作。我知道一个事实,即createAction函数接受一个带有类型键的对象。我没有选择了。请帮助!
1条答案
按热度按时间5n0oy7gb1#
虽然这不是对您的问题的 * 直接 * 回答,但我有一些关于如何改进代码的建议。
首先,使用Redux Toolkit的
configureStore
API,您不必自己设置和编写所有中间件。第二,作为一般观察:我们特别建议 * 反对 * 使用Immutable.js,而建议您 * 应该 * 使用Immer进行不可变更新:
更具体地说,Redux Toolkit的
createSlice
API已经内置了Immer。它还自动为您生成动作创建者和动作类型,因此您不必自己编写任何这些内容:最后,Redux Toolkit包括我们的“RTK Query”数据获取和缓存API,它可以消除为获取数据而编写 * 任何 * 操作、thunk、中间件、reducer或效果的需要:
例如,所有这些文件 * 很可能 * 被替换为:
将RTK查询API中间件和Reducer添加到存储设置中,在组件中使用查询挂钩,* 所有 * 数据获取和缓存都将自动完成!