Angular 2 redux 和 immutable.js 状态

标签 angular redux immutable.js

我使用 ng2-redux 并试图使 redux 状态不可变。我做不到,因为我不知道不可变状态实现了哪个接口(interface)。

比如我有一个redux状态:

let IState = {
    a: {
        b: string
    };
    d: string;
};

let state: IState  = {
  a: {
    b: 'c'
  },
  d: 'e'
}

那么不可变状态是:

let immutableState = Immutable.fromJS(state);

或者也许:

let immutableState = Immutable.Map(state);

我应该知道使用 redux 的不可变状态接口(interface):

constructor(ngRedux: NgRedux<IState>) {

最佳答案

如果您不想使用通用的 Immutable.Map,您可以使用 Immutable.js Record 来创建一个类。

例如

// define an interface
interface IState = {
    a: {
        b: string
    };
    d: string;
};

// next, use the Record constructor passing in the defaults for the class
const stateRecord = Record({
  a: null,
  d: ''
});

// construct a class that extends the return from the Record call
export class MyState extends stateRecord implementsIState {
  a: Map<string, string>;
  d: string;
  constructor(config: IState) {
    super(config);
  }
}

然后在您的 NgRedux 中使用您创建的类。

constructor(ngRedux: NgRedux<MyState>) { ...

由于您正在扩展 stateRecord,因此该类是不可变的。有关 Records 如何在 ImmutableJs 文档中工作的更多信息,请访问 https://immutable-js.github.io/immutable-js/docs/#/Record

关于Angular 2 redux 和 immutable.js 状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39826005/

相关文章:

javascript - 在 ReactJS 导出中组合多个对象

javascript - 可以将 Immutable.js Map 转换为 React 组件内的对象吗

immutable.js - 如何在 immutable.js 列表中使用 setIn

javascript - 使用 redux-saga 删除项目

javascript - 如何从Angular中的错误中恢复

react-native - 为什么没有使用 React Native Router Flux + Redux 触发 React Native Drawer?

javascript - 扩展 Immutable 中的属性

git - 如何解决 Dokku 部署中的 pre-receive hook denied 错误?

angular - 延迟加载,无 block - Angular 7

html - Angular Material 2 : mat-button css to look like mat-button-toggle