错误:操作必须是普通对象。使用自定义中间件进行异步操作

时间:2018-03-29 14:09:30

标签: reactjs redux axios middleware redux-thunk

我有以下代码,抛出操作的错误必须是普通的对象。我认为问题是与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;

1 个答案:

答案 0 :(得分:2)

看起来这是Thunk初始化到商店的方式 - 增强器应该是第三个参数。

来自docs

  

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

     

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

以下是我在项目中对其进行初始化的方法,并指出我以与您在代码中定义的方式类似的方式导入了<h3><a href="#">{{ question.user }}</a></h3> <h3>{{ question.question_html|safe }}</h3> <h3>{{ question.answer_html|safe }}</h3> <a href="{% url 'questions:update' slug=question.slug pk=question.pk %}">Update Question</a> 对象:

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) )) ,但如果你不想要这个额外的功能{@ 3}}或Redux Devtools,如果没有任何东西要编写。< / p>