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

时间:2019-08-01 10:00:30

标签: reactjs react-native redux react-redux

我试图将我的本机代码设为prittier,并尝试通过以下方式将Actions用作新动作:

操作:

ERROR: SEVERE: Servlet.service() for servlet [WebApp] in context with path [/WebApp] threw exception [
Exception executing consequence for rule "conflictingStartBusTooSmall" in com.webapp.jersey: java.lang.IllegalStateException:
  The constraintMatchTotal (com.webapp.jersey/conflictingStartBusTooSmall=-97hard/0medium/0soft)
  could not add constraintMatch (com.webapp.jersey/conflictingStartBusTooSmall/[CloudRoute-83435, CloudBus-17]=-1hard/0medium/0soft)
  to its constraintMatchSet ([
    com.webapp.jersey/conflictingStartBusTooSmall/[CloudRoute-83555, CloudBus-3]=-22hard/0medium/0soft,
    com.webapp.jersey/conflictingStartBusTooSmall/[CloudRoute-83580, CloudBus-3]=-4hard/0medium/0soft,
    com.webapp.jersey/conflictingStartBusTooSmall/[CloudRoute-83594, CloudBus-3]=-8hard/0medium/0soft,
    com.webapp.jersey/conflictingStartBusTooSmall/[CloudRoute-83753, CloudBus-3]=-1hard/0medium/0soft,
    com.webapp.jersey/conflictingStartBusTooSmall/[CloudRoute-83479, CloudBus-4]=-6hard/0medium/0soft,
--> com.webapp.jersey/conflictingStartBusTooSmall/[CloudRoute-83435, CloudBus-6]=-1hard/0medium/0soft,
    com.webapp.jersey/conflictingStartBusTooSmall/[CloudRoute-83429, CloudBus-8]=-26hard/0medium/0soft,
    com.webapp.jersey/conflictingStartBusTooSmall/[CloudRoute-83610, CloudBus-8]=-17hard/0medium/0soft,
    com.webapp.jersey/conflictingStartBusTooSmall/[CloudRoute-83403, CloudBus-10]=-11hard/0medium/0soft
  ]).
] with root cause

所以reducer看起来像这样:

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;

但是现在出现奇怪的错误:当我尝试通过以下方式使用动作时:

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

调用 increment 操作很好,但是调用 decrement 操作会导致错误:const increment = () => ({ type: 'example/INCREMENT_ACTION' }); const decrement = () => new ExampleDecrementAction(); const mapDispatchToProps = (dispatch: any) => { return bindActionCreators({ increment, decrement }, dispatch); };

我的问题:是否可以使用新的类对象作为操作?我在做什么错?

1 个答案:

答案 0 :(得分:0)

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

  

是否可以使用新的类对象作为操作?

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

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

或者在每个动作级别的动作创建者中完成

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