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

时间:2017-08-22 19:42:23

标签: javascript react-redux redux-thunk

我尝试在学习反应,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;
  }
};

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

3 个答案:

答案 0 :(得分:1)

您需要在此处执行两项操作: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()

答案 1 :(得分:0)

您可以使用redux-thunk库,它可以访问“getState”和“dispatch”方法。我看到陈曦已经在你的问题中添加了这个内容。首先在您的操作中运行异步操作,然后使用简单的操作动作创建器调用“dispatch”,这将返回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”动作创建器。

答案 2 :(得分:0)

您应该使用dispatch for async function。看一下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);