【问题标题】:Error: Actions must be plain objects. Use custom middleware for async actions错误:操作必须是普通对象。使用自定义中间件进行异步操作
【发布时间】:2018-03-29 14:09:29
【问题描述】:

我有以下代码,它抛出的错误必须是普通对象。我认为问题出在 redux thunk 但我无法纠正它。

动作文件-

import axios from "axios";
export const addBiller = (biller = {}) => {
return async dispatch => {
const res = await axios.post("/api/biller", biller);

dispatch({ type: "ADD_BILLER", payload: res.data });
};
};

我的商店-

import { createStore, combineReducers, applyMiddleware } from "redux";
import billerReducer from "../reducers/Billers";
import userReducer from "../reducers/User";
import billReducer from "../reducers/Bills";
import authReducer from "../reducers/Auth";
import reduxThunk from "redux-thunk";
export default () => {
 const store = createStore(
combineReducers(
  {
    Billers: billerReducer,
    Users: userReducer,
    Bills: billReducer,
    Auth: authReducer
  },
  applyMiddleware(reduxThunk)
  )
  );
 return store;
 };

后端文件-

 const mongoose = require("mongoose");
 const Biller = mongoose.model("biller");
 module.exports = app => {
 app.post("/api/biller", async (req, res) => {
 const { billerName, billerDescription } = req.body;
 const biller = new Biller({
  billerName: billerName,
  billerDescription: billerDescription
  });
   biller = await biller.save();
    res.send(biller);
    });
     };

我的减速机-

   const BillerDefaultState = [];
   const billerReducer = (state = BillerDefaultState, action) => {
    switch (action.type) {
    case "ADD_BILLER":
     return [...state, action.biller];
     default:
      return state;
     }
     };
     export default billerReducer;

【问题讨论】:

  • 您的 createStore 方法错误。完成 combineReducers 函数,然后将中间件作为第三个参数传递给 createStore 方法。
  • createStore 的第二个参数是预加载状态。 vampurrmaid 的解决方案应该可以帮助您。

标签: reactjs redux axios middleware redux-thunk


【解决方案1】:

看起来这就是 Thunk 被初始化到存储中的方式 - 增强器应该是第三个参数。

来自docs

createStore(reducer, [preloadedState], [enhancer])

[enhancer](功能):存储增强器。您可以选择指定它以使用第三方功能(例如中间件、时间旅行、持久性等)来增强存储。Redux 附带的唯一存储增强器是 applyMiddleware()。

这是我在项目中初始化它的方式,注意我已经以与您在代码中定义它的类似方式导入了 reducers 对象:

import { createStore, applyMiddleware, compose } from 'redux'
import reduxThunk from 'redux-thunk'

const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose
const store = createStore(reducers, {}, composeEnhancers(
  applyMiddleware(reduxThunk)
))

请注意,我还添加了 Redux Devtools,但如果您不想要这个额外的功能,you can just stick to composeapplyMiddleware 如果没有可编写的内容,请单独添加。

【讨论】:

    猜你喜欢
    • 2018-01-30
    • 2018-02-24
    • 2020-11-05
    • 2019-12-26
    • 2020-11-09
    • 1970-01-01
    • 2021-11-04
    • 2020-04-18
    • 1970-01-01
    相关资源
    最近更新 更多