changing the store state from component ngrx

こ雲淡風輕ζ 提交于 2019-12-12 16:54:52

问题


I'm using selectors to select from the store

this.quizz = this.store.select(getSelectedQuizz);

I use the async pipe to read from this observable like this in the template

[*ngIf="quizz | async; let quizz"]

I only define the action and I didn't modify the reducer yet the template is a form when I save the form I dispatch an update action which is only defined in my actions with readonly but I notice that when ever I save the form and dispatch the action the store changed and I didn't specify any logic in the reducer to update the state for the update action yet I don't understand why.


回答1:


You are using 2-way data-binding to bind store state to a form which is a bad practice.
Don't touch anything inside store state except by reducers.

Use spread operator to take a copy of state:

this.store.select(getSelectedQuizz).subscribe(quizz => 
    this.quizzModel = {...quizz };
);

Also take care about deep copies. Use something like this.quizzModel = JSON.parse(JSON.stringify(quizz )); for deep copy.

Hint: To avoid such kind of mistakes you can force state to be immutable. Check ngrx-store-freeze



来源:https://stackoverflow.com/questions/51016496/changing-the-store-state-from-component-ngrx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!