简体   繁体   English

Ngrx 如何在 OnPush 策略中触发 Angular 的 Change Detection

[英]How does Ngrx triggers Angular's Change Detection in OnPush strategy

With Angular OnPush strategy, the change detection gets triggered only if an @Input() variable is changed by ref.使用 Angular OnPush 策略,仅当 @Input() 变量被 ref 更改时才会触发更改检测。

However when using Ngrx, we subscribe to the store's selectors, and Angular's OnPush strategy detect changes in these subscriptions even if they're not passed in input variables.然而,当使用 Ngrx 时,我们订阅了 store 的选择器,Angular 的 OnPush 策略会检测这些订阅的变化,即使它们没有传入输入变量。

My question is how does this work?我的问题是这是如何工作的? How is it that with OnPush strategy Angular detect changes in Ngrx store without them being passed through input variables?如何使用 OnPush 策略 Angular 检测 Ngrx 存储中的变化而不通过输入变量传递它们?

I tried searching for the answer in the api, then tried to scan Ngrx code in Github, but had no luck so far.我尝试在 api 中搜索答案,然后尝试扫描 Github 中的 Ngrx 代码,但到目前为止没有运气。 If you know where is the piece of Ngrx code responsible for this that I'm missing in source code you'd would make my day.如果您知道我在源代码中缺少的负责此问题的 Ngrx 代码在哪里,您会很高兴的。

OnPush does not search an object tree for changes if the reference to the object does not change.如果对 object 的引用没有更改,则 OnPush 不会搜索 object 树的更改。

prop = { val: 1 };

and in the template并在模板中

{{ prop.val }}

If you are using OnPush如果您使用 OnPush

prop.val = 2;

will not update the binding because it will not check the object for changes as it is the same reference.不会更新绑定,因为它不会检查 object 的更改,因为它是相同的参考。

You would need to use你需要使用

prop = { val: 2 };

As the reducer in NgRx should be using pure functions that do not mutate objects but creates new instances of objects you should be confident in using OnPush change detection.由于 NgRx 中的 reducer 应该使用不会改变对象但会创建对象的新实例的纯函数,因此您应该对使用 OnPush 更改检测充满信心。

Don't take the path to poisoning your project with the madness that lies down the path of NgRx.不要走上 NgRx 路径上的疯狂来毒害你的项目的路径。 Redux does not belong in the Angular eco system. Redux 不属于 Angular 生态系统。 Learn RxJs and how to develop well constructed services with behavior subjects and you can also use OnPush if your behavior subjects only emit new objects rather than mutating objects.学习 RxJs 以及如何使用行为主体开发构造良好的服务,如果您的行为主体只发出新对象而不是变异对象,您也可以使用 OnPush。

Angular needs to shake this common misconception that NgRx is the goto Angular state management pattern. Angular 需要改变这种常见的误解,即 NgRx 是 goto Angular state 管理模式。 I was at a talk by Mike Ryan from the NgRx core team a few weeks ago and my question was about how he felt about this misconception and how many newbs jump straight in to using it, his response was that over use was something the team needs to address.几周前我参加了 NgRx 核心团队的 Mike Ryan 的一次演讲,我的问题是关于他对这种误解的看法以及有多少新手直接使用它,他的回答是过度使用是团队需要的东西讲话。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM