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

标签 javascript react-redux redux-thunk

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

在组件中将挂载

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
      };
    });
};

在 reducer 中

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;
  }
};

我得到的是 Actions must be plain objects。使用自定义中间件进行异步操作。

最佳答案

您应该为异步函数使用分派(dispatch)。查看 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);

关于javascript - React Redux - 操作必须是普通对象。使用自定义中间件进行异步操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45825774/

相关文章:

reactjs - 如何启动和打开电子邮件客户端 ReactJS

javascript - 完全获取数据后加载状态变化

javascript - 在某些情况下从数组中删除对象

reactjs - React js 路由器在部署时无法通过 url 正确路由到页面

reactjs - Jest 中的 API 模拟后 useEffect 中的无限循环

javascript - 使用 redux + redux thunk 等待后台任务的惯用方式

reactjs - Redux 工具包更新 thunk 中的状态

javascript - 单击时隐藏/关闭(下一个)div,但有可能显示多个 div

javascript - 跨框架可拖动 + 可排序的鼠标偏移量无效

javascript - 使用 jQuery 在 n 个元素后插入一个 div