Angular ngrx 存储理解来自 Reselect 的 return 值

Angular ngrx store understanding the return value from Reselect

当我将 reselect 与来自 ngrx 的 store.select() 一起使用时,我正试图了解幕后发生的事情。

我知道 select() 方法希望您 return 从您想要 return 的状态开始。例如:

store.select(state => state.articles.isLoading);

对于 Reselect 它将是这样的:

// articles.reducer
const getIsLoading = state => state.isLoading

// root.ts
const getArticlesState = state => state.articles;
const getIsLoading = createSelector(getArticlesState, fromArticles.getIsLoading)

//component.ts
store.select(fromRoot.getIsLoading)

我想了解最后一块发生了什么:

store.select(fromRoot.getIsLoading)

fromRoot.getIsLoading return是值还是函数?

来自 reselect documentation

Selectors are efficient. A selector is not recomputed unless one of its arguments change

此外,您应该阅读:https://github.com/reactjs/reselect#motivation-for-memoized-selectors

也就是说,reselect 在内部使用了一个名为 memoization 的进程。所以发生的事情是它保存了选择器的输出,每次触发选择器时,它都会检查传递给选择器的参数是否相同,如果是,reselect 只是 returns缓存的结果,而不是遍历并再次计算您的数据。

这就是为什么如果您规范化数据然后需要使用选择器组合它们,那么这个库真的很有趣。

另外,当 reselect returns 缓存值时,由选择器组成的 array/objects 不会更改它们的引用,Angular 可以使用该信息并避免触发重绘。这当然比更新商店时重新粉刷所有东西要快。

选择器 getIsLoading return 是一个值。它的价值来源很重要。

选择器会缓存它 returned 的最后一个值。此外,它还会跟踪作为其转换函数参数的商店切片是否发生更改。

如果store改变了,它会重新运行转换函数,缓存它得到的值并return它。

如果存储没有改变,它会return直接缓存值。