【问题标题】:Redux + modify state outsite reducer + angularRedux + 修改状态外地reducer + angular
【发布时间】:2018-04-30 23:21:27
【问题描述】:

有些东西我用 redux 做不到。我在 Angular 项目中使用 ngRedux。

假设我有一家类似的商店:

export interface IState {
    myVar: any
}

export const INITIAL_STATE: IState {
    myVar: {
        value1: 0,
        value2: true
    }
}

如果我使用 @select 装饰器获得了这块商店并订阅了 observable:

@select('myVar') myVar$;

ngOnInit() {
    myVar$.subscribe((myvar) => {
        console.log("myVar changed")
    })
}

是什么阻止我这样做:

@select('myVar') myVar$;

ngOnInit() {
    myVar$.subscribe((myvar) => {
        myvar.value2 = false; // <= This Modify the state
    })
}

我同意我永远不应该这样做,这只是为了举例,但是有没有办法防止这样做呢? 可能会告诉 ngRedux 返回 readonly myVar 或其他内容,因为在更复杂的示例中,这样很容易搞砸商店。

我的实际问题:

public class AnotherClass {

    protected value1: number;
    protected value2: boolean;

    constructor(obj: any) {
        this.value1 = obj.value1;
        this.value2 = obj.value2;
    }
}

public class MyVarWrapper: extends AnotherClass {

    constructor(myvar: any) {
        super(myvar);

        this.value2 = false; // <= [1] Modifying value2
    }
}

@select('myVar') myVar$;

ngOnInit() {
    myVar$.subscribe((myvar) => {
        let wrapper = new MyVarWrapper(myvar); // <= [2] Because of [1] modify the state
    });
}

因为所有这些都是参考,所以商店被修改了,我希望 IDE 的编译器告诉我我在这里搞砸了。 或者更好的是,redux 会返回这个 var 的副本,我可以使用和修改它,而不会冒险修改我的状态。

【问题讨论】:

    标签: angular typescript redux


    【解决方案1】:

    也许这个库会有所帮助: https://github.com/buunguyen/redux-freeze

    它是 Redux 中间件,可防止状态在应用程序的任何地方发生变异。

    还有替代库: https://github.com/brandonroberts/ngrx-store-freeze

    【讨论】:

    • 谢谢,这就是我要找的!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 2019-07-28
    • 1970-01-01
    • 1970-01-01
    • 2020-04-16
    • 2018-08-09
    • 2018-08-04
    相关资源
    最近更新 更多