从组件ngrx更改存储状态 [英] changing the store state from component ngrx

查看:93
本文介绍了从组件ngrx更改存储状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用选择器从商店中进行选择

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"]

我只定义动作,但没有修改reducer,但模板是表单,当我保存表单时,我调度了一个更新动作,该动作仅在我的动作中以readonly定义,但是我注意到,每当保存该动作时,形成并调度商店更改的动作,我没有在化简器中指定任何逻辑来更新更新动作的状态,但我不明白为什么.

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.

推荐答案

您正在使用2向数据绑定将存储状态绑定到一种不好的习惯形式.
不要触摸存储内部的任何内容状态,除减速器外.

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 };
);

还要注意深拷贝.使用类似this.quizzModel = JSON.parse(JSON.stringify(quizz ));的内容进行深度复制.

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

提示: 为了避免此类错误,您可以强制状态不可变. 检查 ngrx-store-freeze

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

这篇关于从组件ngrx更改存储状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆