错误:操作必须是纯对象.使用自定义中间件执行异步操作.如何修复



我对redux操作有问题。当我提交表格时,会显示以下错误。网络显示数据已传输。如何修复?我不知道错误可能在哪里了

我的错误

Error: Actions must be plain objects. Use custom middleware for async actions.
19 | const handleSumbitAddExpenses = (values) => {
20 |   console.log(allCategories);
21 |   allCategories.forEach(category => {
> 22 |     addExpenses({
| ^  23 |       categoryId: category.categoryId,
24 |       data: values,
25 |     })

18 | 
19 |      const handleSumbitAddExpenses = (values) => {
20 |        console.log(allCategories);
> 21 |        allCategories.forEach(category => {
| ^  22 |          addExpenses({
23 |            categoryId: category.categoryId,
24 |            data: values,```

Redux Action

export const addExpenses = ({categoryId, data}) => async(dispatch) => {
dispatch({
type: ADDEXPENSES_GET_REQUEST,
})
try {
const response = await API.expenses.addExpenses({
categoryId,
data
});
const data = await response.json();
dispatch({
type: ADDEXPENSES_GET_SUCCES,
payload: data,
})
}catch (error) {
dispatch({
type: ADDEXPENSES_GET_FAILURE,
})
}
}

组件中的功能

const handleSumbitAddExpenses = (values) => {
console.log(allCategories);
allCategories.forEach(category => {
addExpenses({
categoryId: category.categoryId,
data: values,
})
})

}

这是我的商店设置。redux thunk文档中的简单设置。

import { applyMiddleware, createStore } from "redux";
import { composeWithDevTools } from "redux-devtools-extension";
import thunkMiddleware from "redux-thunk";
import rootReducer from "./reducers";
export default function configureStore(preloadedState) {
const middlewares = [thunkMiddleware];
const middlewareEnhancer = applyMiddleware(...middlewares);
const enhancers = [middlewareEnhancer];
const composedEnhancers = composeWithDevTools(...enhancers);
const store = createStore(rootReducer, preloadedState, composedEnhancers);
if (process.env.NODE_ENV !== "production" && module.hot) {
module.hot.accept("./reducers", () => store.replaceReducer(rootReducer));
}
return store;
}

和我的提取

export const addExpenses = ({ categoryId, data }) => {
const promise = fetch(
`
${process.env.REACT_APP_API_URL}/categories/${categoryId}/transactions`,
{
method: "POST",
headers: {
"Content-type": "application/json",
},
body: JSON.stringify(data),
}
);
return promise;
};

首先redux操作应该只返回普通对象。然而,您将返回另一个函数,该函数将dispatch作为参数来运行一些异步代码。

这种操作实现是redux-thunk中间件的典型实现。如果您返回另一个函数,redux-thunk会截获调度调用,使您能够发出异步请求。但首先您需要安装redux thunknpm install redux-thunk,然后在创建商店时将其作为中间件应用,如:

import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers/index';
const store = createStore(rootReducer, applyMiddleware(thunk));

一旦您的中间件得到了正确的实现,那么进行异步调用的操作应该可以按预期工作。

最新更新