React Redux - 操作必须是普通对象。使用自定义中间件进行异步操作

React Redux - Actions must be plain objects. Use custom middleware for async actions

我尝试在我的学习 react、redux 项目中使用 axom 处理 ajax 数据,但我不知道如何分派一个动作并设置组件内的状态

在组件中将挂载

componentWillMount(){
  this.props.actions.addPerson();
}

商店

import { createStore, applyMiddleware } from "redux";
import rootReducer from "../reducers";
import thunk from "redux-thunk";

export default function configureStore() {
  return createStore(rootReducer, applyMiddleware(thunk));
}

在行动:

import * as types from "./action-types";
import axios from "axios";
export const addPerson = person => {
  var response = [];

  axios
    .get(`&&&&&&&&&&&`)
    .then(res => {
      response = res.data;

      return {
        type: types.ADD_PERSON,
        response
      };
    });
};

在减速器中

import * as types from "../actions/action-types";

export default (state = [], action) => {
  console.log("action======>", action);
  switch (action.type) {
    case types.ADD_PERSON:
      console.log("here in action", action);
      return [...state, action.person];
    default:
      return state;
  }
};

我收到操作必须是普通对象。使用自定义中间件进行异步操作。

您使用 redux-thunk 库,它使您可以访问 "getState" 和 "dispatch" 方法。我看到 Chenxi 已将其添加到您的问题中。 运行 你的异步操作首先在你的动作中,然后用你的简单动作动作创建者调用 "dispatch",这将 return redux 正在寻找的简单对象。

异步动作创建器和简单动作创建器(分为两个动作创建器)如下所示:

export const addPersonAsync = (person) => {
  return (dispatch) => {
    var response = [];

    axios
      .get(`http://599be4213a19ba0011949c7b.mockapi.io/cart/Cart`)
      .then(res => {
        response = res.data;

        dispatch(addPerson(response));
      });
  };
};


export const addPerson = (response) => ({
  type: types.ADD_PERSON,
  response
});

从您的组件中,您现在将调用 "addPersonAsync" 动作创建器。

您需要在此处执行两项操作:postPersonaddPerson

postPerson 将执行 API 请求并且 addPerson 将更新商店:

const addPerson = person => {
    return {
        type: types.ADD_PERSON,
        person,
    }
}

const postPerson = () => {
   return (dispatch, getState) => {
       return axios.get(`http://599be4213a19ba0011949c7b.mockapi.io/cart/Cart`)
                   .then(res => dispatch(addPerson(res.data)))
   }
}

在您的组件中,调用 postPerson()

您应该为异步函数使用分派。查看 redux-thunk 的文档:https://github.com/gaearon/redux-thunk

在行动:

import * as types from "./action-types";
import axios from "axios";

export const startAddPerson = person => {
  return (dispatch) => {
    return axios
      .get(`https://599be4213a19ba0011949c7b.mockapi.io/cart/Cart`)
      .then(res => {
        dispatch(addPersons(res.data));
      });
  }
};

export const addPersons = personList => {
  return {
    type: types.ADD_PERSON,
    personList
  };
}

在 PersonComponent 中:

class Person extends Component {
  constructor(props){ 
    super(props);
  }
  componentWillMount() {
    this.props.dispatch(startAddPerson())
  }

  render() {
    return (
      <div>
      <h1>Person List</h1>
      </div>
    );
  }
}

export default Redux.connect()(Person);