【问题标题】:typescript redux: how to reduce boilerplate with typesafe-actionstypescript redux:如何使用 typesafe-actions 减少样板文件
【发布时间】:2019-12-26 14:16:12
【问题描述】:

我正在使用带有 typesafe-actions 的 typescript。 我的代码库有很多重复的代码,如下所示: 我查看了类似的问题,但找不到答案。

如何减少样板。

import { action, ActionType, createAction } from 'typesafe-actions';

interface ModelA {
  stuff: string
}

export enum FeatureAActionTypes {
  Load = '[FeatureA] Load',
  Success = '[FeatureA] Success',
  Fail = '[FeatureA] Fail',
  Reset = '[FeatureA] Reset'
}

export const FeatureAActions = {
  load: createAction(FeatureAActionTypes.Load),
  success: (response: ModelA[]) => action(FeatureAActionTypes.Success, response),
  fail: (error: string) => action(FeatureAActionTypes.Fail, error),
  reset: createAction(FeatureAActionTypes.Reset)
};

export type FeatureAAction = ActionType<typeof FeatureAActions>;

interface ModelB {
  differentStuff: string
}

export enum FeatureBActionTypes {
  Load = '[FeatureB] Load',
  Success = '[FeatureB] Success',
  Fail = '[FeatureB] Fail',
  Reset = '[FeatureB] Reset'
}

export const FeatureBActions = {
  load: createAction(FeatureBActionTypes.Load),
  success: (response: ModelB[]) => action(FeatureBActionTypes.Success, response),
  fail: (error: string) => action(FeatureBActionTypes.Fail, error),
  reset: createAction(FeatureBActionTypes.Reset)
};

export type FeatureBAction = ActionType<typeof FeatureBActions>;

【问题讨论】:

标签: typescript redux typesafe-actions


【解决方案1】:

鉴于该库已经设计为减少样板代码,您越能坚持使用 API,您需要编写的样板代码就越少。如果您使用内置的createReducer API,有一种方法可以避免将您的操作类型定义为字符串的需要。也就是说,它们是从 createAction 返回的动作创建者推断出来的。

您保留这些单独的 似乎 暗示您正在使用自己的减速器,这几乎肯定是您还导出所有 FeatureXAction 类型的原因。这可以在最后完成,而不是单独完成,但实际上只会为每个文件节省一行,并且您仍然需要在最后聚合它们。所有这些都会增加冗长和样板。

在 typesafe-actions 之前,我们的样板文件比您还要多,因为我们的每个操作都由一个接口定义,然后每个操作创建者返回该接口的实现。虽然它非常明确,但非常冗长。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-09-22
    • 2020-03-31
    • 2019-09-16
    • 1970-01-01
    • 1970-01-01
    • 2013-03-23
    • 1970-01-01
    相关资源
    最近更新 更多