【问题标题】:Action must be plain objects. Use custom middleware for async actions动作必须是普通对象。使用自定义中间件进行异步操作
【发布时间】:2019-08-01 10:00:30
【问题描述】:

我正在尝试使我的 react-native 代码更简洁,并尝试通过以下方式将 Actions 用作新操作:

行动:

import { Action } from "redux";

export const actionType = {
  INCREMENT_ACTION: "example/INCREMENT_ACTION",
  DECREMENT_ACTION: "example/DECREMENT_ACTION"
};

export class ExampleIncrementAction implements Action {
  type = actionType.INCREMENT_ACTION;
}

export class ExampleDecrementAction implements Action {
  type = actionType.DECREMENT_ACTION;
}

export type ExampleActions = ExampleIncrementAction | ExampleDecrementAction;

reducer 可以是这样的:

export default function exampleReducer(
  state = initialState,
  action: ExampleActions
) {
  switch (action.type) {
...

但是现在出现了奇怪的错误:当我尝试按以下方式使用操作时:

const increment = () => ({ type: 'example/INCREMENT_ACTION' });
const decrement = () => new ExampleDecrementAction();

const mapDispatchToProps = (dispatch: any) => {
  return bindActionCreators({ increment, decrement }, dispatch);
};

调用increment动作没问题,但是调用decrement动作会报错:Action must be plain objects. Use custom middleware for async actions.

我的问题:有没有办法使用新的类对象作为操作?我做错了什么?

【问题讨论】:

    标签: reactjs react-native redux react-redux


    【解决方案1】:

    Redux 在设计上只接受普通对象作为操作以避免各种可能的错误。例如,将 Promise 作为操作传递。

    有没有办法将新的类对象用作操作?

    要将某些类实例用作操作,您可以实现自定义中间件来克服此限制(如果有人说将 Promise 作为操作分派,这可能会在未来导致错误)

    const useCustomActions = state => next => action => next({ ...action })
    

    或者在每个动作级别的动作创建器中进行操作

    const decrement = () => ({...new ExampleDecrementAction()});
    

    【讨论】:

      猜你喜欢
      • 2020-06-17
      • 1970-01-01
      • 2018-02-19
      • 2018-11-12
      • 2018-01-31
      • 2018-03-27
      • 1970-01-01
      • 2018-02-24
      相关资源
      最近更新 更多