NgRx选择器在状态发生任何变化/选择器的记忆不起作用时发出 [英] NgRx selector emits when anything on the state changes/memoization of selector not working

查看:62
本文介绍了NgRx选择器在状态发生任何变化/选择器的记忆不起作用时发出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将Angular 7和NgRx一起使用.我创建了一个选择器以使用filter从存储中获取一些数据,但是当存储中的任何内容发生更改时,即使该选择器与我的选择器无关,该选择器也会发出.

I'm using Angular 7 along with NgRx. I have created a selector to get some data from the store using filter, but this selector emits when anything on the store changes, even if it is not related to my selector.

我已经演示了我的问题.这是我的选择器:

I have created a demonstration of my issue. Here is my selector:

export const getMyArrayFilter = createSelector(
    getCounterState,
    state => state.myArray.filter(x => x === 'new Item')
);

在这里,我使用我的getMyArrayFilter选择器:

And here I am using my getMyArrayFilter selector:

this.store.pipe(select(fromRoot.getMyArrayFilter)).subscribe(x => console.log(x));

但是如上所述,此selector会在状态发生任何变化时随时发出.

But as mentioned, this selector will emit anytime anything changes on the state.

请查看 StackBlitz演示.

Please take a look at this StackBlitz demonstration.

如果您尝试单击将项目添加到数组"或-"或"+"按钮,则我的getMyArrayFilter将发出并每次登录到控制台.如果状态更改myArray,我的选择器是否应该仅发出值?

If you try clicking on either the "Add item to array" or "-" or "+" buttons, then my getMyArrayFilter will emit, and log to the console each time. Should't my selector only emit values IF the myArray on my state changes?

我查看了这个 SOF问题,其中提到使用distinctUntilChanged,但这似乎对我不起作用.

I have taken a look at this SOF question which mentions using distinctUntilChanged but that doesn't seem to work for me.

推荐答案

正如Alejandro所指出的,这是因为myArray有一个新的引用. 您可以根据需要修改备忘录,Alex Okrushko在他的演讲中完全做到了这一点 NgRx :选择器比您想象的更强大

As Alejandro pointed out, this is because there's a new reference for myArray. You can modify the memoization to your needs, Alex Okrushko does exactly this in his talk NgRx: Selectors are more powerful than you think

这篇关于NgRx选择器在状态发生任何变化/选择器的记忆不起作用时发出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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