我使用 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/